🖥️bash

➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the bash command with important options and switches using examples.

▁ ▂ ▃ ▄ ꧁ 🔴☠ COMMANDLINE-KUNGFU WITH CHEATSHEETS ☠🔴꧂▅ ▃ ▂ ▁

#                ██████╗  █████╗ ███████╗██╗  ██╗
#                ██╔══██╗██╔══██╗██╔════╝██║  ██║
#                ██████╔╝███████║███████╗███████║
#                ██╔══██╗██╔══██║╚════██║██╔══██║
#                ██████╔╝██║  ██║███████║██║  ██║
#                ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝
                                                
                                               
															  
															  
#==============================#
# CMD BASH
#==============================##==============================#
# To implement a for loop:
for file in *;
do 
    echo $file found;
done

# To implement a case command:
case "$1"
in
    0) echo "zero found";;
    1) echo "one found";;
    2) echo "two found";;
    3*) echo "something beginning with 3 found";;
esac

# Turn on debugging:
set -x

# Turn off debugging:
set +x

# Retrieve N-th piped command exit status
printf 'foo' | fgrep 'foo' | sed 's/foo/bar/'
echo ${PIPESTATUS[0]}  # replace 0 with N

# Lock file:
( set -o noclobber; echo > my.lock ) || echo 'Failed to create lock file'

# Fork bomb
:(){ :|:& };:

# Unix Roulette
# (Courtesy of Bigown's answer in the joke thread)
# DANGER! Don't execute!
[ $[ $RANDOM % 6 ] == 0 ] && rm -rf /* || echo Click #Roulette

# for loop in one line
for i in $(seq 1 4); do echo $i; done

# Check to see if a variable equals a specified integer
if [ "$var" -eq "0" ]; then
    echo "var equals zero";
fi

# Test if a program exists in the path
# There are false positives: aliases and functions
command -v ${program} >/dev/null 2>&1 || error "${program} not installed"

# Redirection
# Please note that 2>&1 goes after
my_command > command-stdout-stderr.txt 2>&1
my_command > /dev/null 2>&1
# Redirect stdout and stderr of cmd1 to cmd2
cmd1 |& cmd2

# Convert spaces to underscores in filenames
for name in *\ *; do mv -vn "$name" "${name// /_}"; done

#==============================#
# CMD BASH
#==============================##==============================#

[Ctrl-d] 
# Last one for today. This indicates to the program that there is no more input. In the shell, this usually closes the shell.

[Ctrl-u] 
# Delete everything from the cursor to the beginning of the line. This can also be used to clear a password attempt and start over.

[Ctrl-w] 
# Delete the previous word on the command line (before the cursor). This is highly useful when reusing old commands.

[Ctrl-l] 
# This is usually equivalent to running 'clear'.  Its usually quicker and does not leave the command in your command line history.

[Ctrl-_] 
# Incremental undo of command line edits.

[Meta-#] 
# Comment out the current command from the beginning of the line. Faster than [Ctrl-a] then #.

[Meta-.] 
# Insert the last argument from the previous line in the command history into the current line. This is different from using !$ Press multiple times to keep going back through each history line's last argument.

[Ctrl-e] 
# Move your cursor to the end of the line. Faster than holding down right arrow.

[Ctrl-a] 
# Move your cursor to the beginning of the line. Faster than holding down left arrow. In screen, you need to press <Ctrl-a a>

[Ctrl-q] 
# Sometimes you may find your terminal window appears "frozen". It's not due to the weather. Try pressing Ctrl-q, if that fixes it, its because you hit Ctrl-s. Note: Unfortunately, pressing Ctrl-q multiple times will probably not send you to Hawaii.

[Ctrl-r]string 
# Reverse search through your command history for 'string'. Press Ctrl-r again to continue searching backwards. ESC when done

[C-M]+e 
# That's Ctrl + Meta + e. This will expand any history references you make (like !-5$) so you can check before running.

(xsel -b || pbpaste) |hexdump -c 
# Dump your paste clipboard to hexdump for character by character investigation of what you just copied.

# Option Mnemonics: tar xzvf = Xtract Ze Vucking Files [said in thick German accent]
# Tip: Sometimes you get yourself into weird situations/trapped signals where Ctrl-C and Ctrl-| do not work. Try Ctrl-z and kill %1.

<ctrl-z> bg ; wait %1 ; echo "done" | mail -s "done" [email protected] 
# You started a program, but now want it to notify you when its done.

longcmd ; [Ctrl-Z] ; bg ; disown ; screen ; reptyr $( pidof longcmd ) 
# Suspend and reattach a process to screen.

# Get executed in script its current working directory
CWD=$(cd "$(dirname "$0")" && pwd)
# Explanation: Will return excuting script's current working directory, wherever Bash executes the script containing this line.

PS1="# $PS1" 
# Make your prompt safer with # so that if you accidentally copy & paste it, it does not run. Based on @pacohope's idea.

# An escaped upper case letter typically means the opposite of its lower case counterpart: \D <-> \d, \S <-> \s, etc.

&>
# bash let you use &> to send stdout and stderr to a file. Version 4 or later.

$^
# In bash, $^ expands to 2nd word of previous command

!?foo
# In bash, !?foo will repeat the most recent command that contained the string 'foo'

^foo^bar
# In bash, ^foo^bar repeats the latest command, replacing the first instance of 'foo' with 'bar'

!$
# In bash, !$ expands to last word of previous command

!:n
# Um das nth Argument der Bash (gezählt von 0) zu erhalten

!$ 
# Um das letzte Argument der Bash zu erhalten 

bash -c 'swapoff -a && swapon -a'
# After killing processing using up all your RAM on Linux (Firefox!!), move processes off of swap.

&>
# bash let you use &> to send stdout and stderr to a file. Version 4 or later.

(cmd1;cmd2;cmd3)
# When running commands in a subshell, you can use job control (Ctrl-C, Ctrl-Z, fg, bg) on the subshell as a whole unit.

:(){ :|:& };: 
# DO NOT RUN THIS FORK BOMB

HISTCONTROL="ignoreboth"
# In bash, this sets the history to ignore commands starting with spaces and duplicates. May already be set.

HISTIGNORE="history;ls;date;w;man *"
# In bash, this will leave history, ls, date, w and man whatever out of your command history.

LANG=C sort 
# Setting the LANG=C variable will often fix unexpected problems with sort ignoring symbol characters like +, - and *

> file.txt
# This command flush the contents of a file without the need of removing and creating the same file again. This command is very useful in scripting language when we need an output or log on the same file again and again.

!#
# Where # should be changed with the actual number of the command. For better understanding, see the below example:

!501
# Command of history line 501

# Bash Shell Handy Cheatsheet
#    ^u            Clears the line before the cursor position. If you are at the end of the line, clears the entire line.
#    ^h            Same as backspace
#    ^w            Delete (cut) the word before the cursor (to the clipboard)
#    ^xx           Move between start of command line and current cursor position (and back again)
#    ^t            Swap the last two characters before the cursor
#    ESC-t         Swap the last two words before the cursor
#    Alt/Opt-c     Capitalize the character under the cursor and move to the end of the word.
#    Alt/Opt-l     Lower the case of every character from the cursor to the end of the current word.
#    Alt/Opt-r     Cancel the changes and put back the line as it was in the history (revert).
#    Alt/Opt-t     Swap current word with previous
#    Alt/Opt-u     UPPER capitalize every character from the cursor to the end of the current word.
#    Alt/Opt-Del   Delete the Word before the cursor.
#
#    !abc:p        Print last command starting with abc
#    !$            (Use) Last argument of previous command
#    !$:p          Print out the word that !$ would substitute
#    Alt/Opt-.     (Get) Last argument of previous command
#    !*            (Use) All arguments of previous command
#    ^abc­^­def     Run previous command, replacing abc with def

timeout 1 bash -c '</dev/tcp/216.58.207.46/443 && echo Port is open || echo Port is closed' || echo Connection timeout
# How to test a TCP (or UDP) remote port without telnet or netcat (in a one-liner): (google’s IP and TCP to 443) 

helpful_bash_commands.txt

## BASH ##
	ctrl-r searches your command history as you type
	!!:n 	# selects the nth argument of the last command, and 
	!$ 	# the last arg 
			ls file1 file2 file3; cat !!:1-2  	# shows all files and cats only 1 and 2
	shopt -s cdspell 									# automatically fixes your 'cd folder' spelling mistakes
	set editing-mode vi 								# in your ~/.inputrc to use the vi keybindings for bash and all readline-enabled applications (python, mysql, etc)
		command < file.in   with command <<< "some input text"
		# Input from the commandline as if it were a file by replacing 
		^ 								# is a sed-like operator to replace chars from last command 'ls docs; ^docs^web^' is equal to 'ls web'. The second argument can be empty.
		nohup ./long_script & 	# to leave stuff in background even if you logout
		cd - 							# change to the previous directory you were working on
		ctrl-x ctrl-e 				# opens an editor to work with long or complex command lines

## PSEUDO ALIASES FOR COMMONLY USED LONG COMMANDS
		function lt() { ls -ltrsa "$@" | tail; }
		function psgrep() { ps axuf | grep -v grep | grep "$@" -i --color=auto; }
		function fname() { find . -iname "*$@*"; }
		function remove_lines_from() { grep -F -x -v -f $2 $1; } # removes lines from $1 if they appear in $2
		function mcd() { mkdir $1 && cd $1; }
		alias pp="ps axuf | pager"
		alias sum="xargs | tr ' ' '+' | bc" 							# Usage: echo 1 2 3 | sum

## VIM
		':set spell' 	# activates vim spellchecker. 
		']s' and '[s' 	# to move between mistakes 
		'zg' 				# adds to the dictionary 
		'z=' 				# suggests correctly spelled words
							# check my .vimrc http://tiny.cc/qxzktw and here http://tiny.cc/kzzktw for more

## TOOLS
	-> htop instead of top
	-> ranger is a nice console file manager for vi fans
	-> Google 'magic sysrq' to bring a Linux machine back from the dead
	-> trash-cli sends files to the trash instead of deleting them forever. 
			Be very careful with 'rm' or maybe make a wrapper to avoid deleting '*' by accident (e.g. you want to type 'rm tmp*' but type 'rm tmp *')

	chmod o+x * -R 
		# Never run capitalize the X to avoid executable files. 

	find . -type d -exec chmod g+x {} \;
		 # If you want _only_ executable folders: 
 
	ls *.png | parallel -j4 convert {} {.}.jpg
		# run jobs in parallel easily
		

	apt-file 		# to see which package provides that file you are missing
	dict				# is a commandline dictionary

		sort | uniq 									# to check for duplicate lines
		echo start_backup.sh | at midnight		# starts a command at the specified time

		diff --side-by-side fileA.txt fileB.txt | pager # to see a nice diff

## NETWORKING
	# Read on 'ssh-agent' to strenghten your ssh connections using private keys, while avoiding typing passwords every time you ssh.
	# Use this trick on .ssh/config to directly access 'host2' which is on a private network, and must be accessed by ssh-ing into 'host1' first Host host2
     ProxyCommand ssh -T host1 'nc %h %p'
  	  HostName host2

tar cz folder/ | ssh server "tar xz" 
	# Pipe a compressed file over ssh to avoid creating large temporary .tgz files or even better, use 'rsync'

	# ssmtp can use a Gmail account as SMTP and send emails from the command line. 
		echo "Hello, User!" | mail [email protected] 
		Configure your /etc/ssmtp/ssmtp.conf:
				root=***E-MAIL***
				mailhub=smtp.gmail.com:587
				rewriteDomain=
				hostname=smtp.gmail.com:587
				UseSTARTTLS=YES
				UseTLS=YES
				AuthUser=***E-MAIL***
				AuthPass=***PASSWORD***
				AuthMethod=LOGIN
				FromLineOverride=YES

                                     -~-

		If you use 'sshfs_mount' and suffer from disconnects, use '-o reconnect,workaround=truncate:rename'
		python -m SimpleHTTPServer 8080 or python3 -mhttp.server localhost 8080 		# shares all the files in the current folder over HTTP. 
		socat TCP4-LISTEN:1234,fork TCP4:192.168.1.1:22 		# forwards your port 1234 to another machine's port 22. Very useful for quick NAT redirection.
		# Some tools to monitor network connections and bandwith: 
			lsof -i monitors network connections in real time 
			iftop shows bandwith usage per *connection* 
			nethogs shows the bandwith usage per *process*
		ssh -R 12345:localhost:22 server.com "sleep 1000; exit" # forwards server.com's port 12345 to your local ssh port, even if you machine  is not externally visible on the net. Now you can 
		ssh localhost -p 12345 # from server.com and you will log into your machine. 'sleep' avoids getting kicked out from server.com for inactivity

# Silently Execute a Shell Script that runs in the background and won't die on HUP/logout
(nohup your-command your-args &>/dev/null &)

# Make your prompt a bit safer with a # prefix so that if you accidentally copy & paste it, at least some lines won't execute.
PS1="# $PS1" 

# Setting the LANG=C variable will often fix unexpected problems with sort ignoring symbol characters like +, - and * or just general weirdness. For instance, I just ran into problems because my LANG was set to en_US.UTF-8.
LANG=C sort 

[ $(( $RANDOM % 2 )) -eq 0 ] && command 
# Run a command unreliably. In other worse, it will run sometimes. Could be useful in cron, but remember to use \% instead of % if using in crontab.

PATH=$PATH:/root 
# Put this in your normal user shell profile and freak out the sysadmin. 

$EDITOR 
# On hosts with access by others, you may wish to keep the file you are working on out of the process table for privacy or even security reasons. In which case you can start the editor first and then open the file from within.

PS1="\t $PS1"  
# Customized your shell prompt in BASH so that it is prefixed with the current time.

stty -echo; grep -F -f- passwords.txt; stty echo 
# Use the -f option with - to read search patterns from stdin. Press [Ctrl-d] twice when done. I used -F here for fixed string to avoid things like . matching all. I do all this to avoid passwords in the process table or history.

# Escape spaces in string
FILE_PATH=$( echo "$FILE_PATH" | sed 's/ /\\ /g' )

# Bash command to get current directory
VAR_NAME=$(pwd)

# COLORS
##############################################
# Black        0;30     Dark Gray     1;30
# Blue         0;34     Light Blue    1;34
# Green        0;32     Light Green   1;32
# Cyan         0;36     Light Cyan    1;36
# Red          0;31     Light Red     1;31
# Purple       0;35     Light Purple  1;35
# Brown/Orange 0;33     Yellow        1;33
# Light Gray   0;37     White         1;37
##############################################

# Set a colorful bash prompt per dev test prod environments
PS1='\[\e[1;31m\][\u@\h \W]\$\[\e[0m\] '
# Explanation: It is useful to set a different color for the shell prompt in different deployment environments like dev/test/production, so that you do not mix up your multiple windows and do something by accident in the wrong window.
        # PS1 contains the format of the primary prompt
        # \[\e[1;31m\] sets the foreground color to red
        # \u will be substituted with the current username
        # \h will be substituted with the hostname
        # \W will be substituted with the current directory name
        # \[\e[0m\] is the end marker of the color setting
	 # To make the color stand out even more for root users, the inverse color can be interesting too:
	 # PS1='\[\e[7;31m\][\u@\h \W]\$\[\e[0m\] '
# Other color examples:
	# PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] ' # green
	# PS1='\[\e[1;33m\][\u@\h \W]\$\[\e[0m\] ' # yellow
	# PS1='\[\e[1;34m\][\u@\h \W]\$\[\e[0m\] ' # blue
# You can learn more in man bash, search for "PROMPTING".
# Limitations: Your terminal program must support colors, of course ;-)

# A one liner to test, getting the contents of the current working directory:
select file in *; do filename="$file"; done; echo you selected $filename

# Tales from malicious scripts.
cd /tmp || cd /var/run || cd /mnt || cd /root || cd / || echo "dude your server is really screwed up, I'm outta here." || exit 

# Redirect the output of multiple commands
{ cmd1 ; cmd2 ; cmd3 ; } > out.out 2> err.out
# Explanation: 
    # Curly braces are very helpful for grouping several commands together
    # Be careful with the syntax: 1. there must be whitespace after the opening brace 2. there must be a semicolon after the last command and before the closing brace
    # Another practical use case: test something || { echo message; exit 1; }

#==============================##==============================#
# CMD bash						       #
#==============================##==============================#
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

  █║▌│║█║▌★ KALI ★ PARROT ★ DEBIAN 🔴 PENTESTING ★ HACKING ★ █║▌│║█║▌

              ██╗ ██╗ ██████╗  ██████╗ ██╗  ██╗███████╗██████╗
             ████████╗██╔══██╗██╔═══██╗╚██╗██╔╝██╔════╝██╔══██╗
             ╚██╔═██╔╝██║  ██║██║   ██║ ╚███╔╝ █████╗  ██║  ██║
             ████████╗██║  ██║██║   ██║ ██╔██╗ ██╔══╝  ██║  ██║
             ╚██╔═██╔╝██████╔╝╚██████╔╝██╔╝ ██╗███████╗██████╔╝
              ╚═╝ ╚═╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═════╝

               █║▌│║█║▌ WITH COMMANDLINE-KUNGFU POWER █║▌│║█║▌

░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░