Bash: Process Handling Cheat Sheet

# To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y.

# This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal.

# Of course, to interupt a job, type CTRL+C.
myCommand &runs the job in the background and prompts back the shell
jobslists all jobs (use with -l to see associated PID)
fgbrings a background job into the foreground
fg %+brings most recently invoked background job
fg %-brings the second most recently invoked background job
fg %Nbrings job number N
fg %stringbrings a job whose command begins with the string
fg %?stringbrings a job whose command contains the string
kill -lreturns a list of all signals on the system, by name and number
kill PIDterminates the process with specified PID
psprints a line of information about the current running login shell and any processes running under it
ps -aselects all processes with a TTY except session leaders
trap cmd sig1 sig2executes a command when a signal is received by the script
trap "" sig1 sig2ignores that signals
trap - sig1 sig2resets the action taken when the signal is received to the default
disown <PID|JID>removes the process from the list of jobs
waitwaits until all background jobs have finished

Bash: Tips and Tricks Cheat Sheet

# set an alias

cd; nano .bash_profile
> alias gentlenode='ssh admin@gentlenode.com -p 3404' # add your alias in .bash_profile

# to quickly go to a specific directory
cd; nano .bashrc

> shopt -s cdable_vars

> export websites="/Users/mac/Documents/websites"
source .bashrc

cd websites

Bash: Debugging Shell Programs Cheat Sheet

bash -n scriptnamedon’t run commands; check for syntax errors only
set -o noexecalternative (set option in the script)
bash -v scriptnameecho commands before running them
set -o verbosealternative (set option in the script)
bash -x scriptnameecho commands after command-line processing
set -o xtracealternative (set option in the script)
trap 'echo $varname' EXITuseful when you want to print out the values of variables at the point that your script exits
function errtrap {
  es=$?
  echo "ERROR line $1: Command exited with status $es."
}
trap 'errtrap $LINENO' ERRis run whenever a command in the surrounding script or function exists with non-zero status
function dbgtrap {
  echo "badvar is $badvar"
}
trap dbgtrap DEBUG# causes the trap code to be executed before every statement in a function or script
# …section of code in which the problem occurs…
trap - DEBUGturn off the DEBUG trap
function returntrap {
  echo "A return occured"
}
trap returntrap RETURN is executed each time a shell function or a script executed with the . or source commands finishes executing

Bash: Basics Cheat Sheet

exportdisplays all environment variables
echo $SHELLdisplays the shell you’re using
echo $BASH_VERSION displays bash version
bashif you want to use bash (type exit to go back to your normal shell)
whereis bashfinds out where bash is on your system
clearclears content on the window (hide displayed lines)
# File Commands.
lslists your files
ls -l ists your files in ‘long format’, which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified
ls -alists all files, including hidden files
ln -s
<filename> <link>
creates a symbolic link to file
touch <filename>creates or updates your file
cat > <filename>places standard input into file
more <filename>shows the first part of a file (move with space and type q to quit)
head <filename>outputs the first 10 lines of a file
tail <filename>outputs the last 10 lines of a file (useful with -f option)
emacs <filename>lets you create and edit a file
mv <filename1> <filename2>moves a file
cp <filename1> <filename2>copies a file
rm <filename>removes a file
diff <filename1> <filename2>compares files, and shows where they differ
wc <filename>tells you how many lines, words, and characters there are in the file
chmod -options <filename>lets you change the read, write, and execute permissions on your files
gzip <filename>compresses files
gunzip <filename>uncompresses files compressed by gzip
gzcat <filename>lets you look at gzipped file without actually having to gunzip it
lpr <filename>print the file
lpqcheck out the printer queue
lprm <jobnumber>remove something from the printer queue
genscriptconverts plain text files into postscript for printing and gives you some options for formatting
dvips <filename>print .dvi files (i.e. files produced by LaTeX)
grep <pattern> <filenames>looks for the string in the files
grep -r <pattern> <dir>search recursively for a pattern in the directory
# Directory Commands.
mkdir <dirname>makes a new directory
cdchanges to home
cd <dirname>changes directory
pwdtells you where you currently are
# SSH, System Info & Network Commands.
ssh user@hostconnects to host as a user
ssh -p <port> user@hostconnects to host on the specified port as user
ssh-copy-id user@hostadds your ssh key to host for a user to enable a keyed or passwordless login
whoamireturns your username
passwdlets you change your password
quota -vshows what your disk quota is
dateshows the current date and time
calshows the month’s calendar
uptimeshows current uptime
wdisplays whois online
finger <user>displays information about the user
uname -ashows kernel information
man <command>shows the manual for the specified command
dfshows disk usage
du <filename>shows the disk usage of the files and directories in the filename (du -s give only a total)
last <yourUsername>lists your last logins
ps -u yourusernamelists your processes
kill <PID>kills (ends) the processes with the ID you gave
killall <processname>kill all processes with the name
topdisplays your currently active processes
bglists stopped or background jobs; resume a stopped job in the background
fgbrings the most recent job in the foreground
fg <job> brings the job to the foreground
ping <host>pings host and outputs results
whois <domain>gets whois information for the domain
dig <domain>gets DNS information for the domain
dig -x <host>reverses lookup host
wget <file>downloads file

Bash: Basic Shell Programming Cheat Sheet

# Variables.
varname=valuedefines a variable
varname=value commanddefines a variable to be in the environment of a particular subprocess
echo $varnamechecks a variable’s value
echo $$prints process ID of the current shell
echo $!prints process ID of the most recently invoked background job
echo $?displays the exit status of the last command
export VARNAME=valuedefines an environment variable (will be available in subprocesses)
array[0] = val
array[1] = val
array[2] = val
array=([2]=val [0]=val [1]=val)
several ways to define an array
${array[i]}displays array’s value for this index. If no index is supplied, array element 0 is assumed
${#array[i]}to find out the length of any element in the array
${#array[@]}to find out how many values there are in the array
declare -athe variables are treated as arrays
declare -fuses function names only
declare -Fdisplays function names without definitions
declare -ithe variables are treated as integers
declare -rmakes the variables read-only
declare -xmarks the variables for export via the environment
${varname:-word}if varname exists and isn’t null, return its value; otherwise return word
${varname:=word}if varname exists and isn’t null, return its value; otherwise set it word and then return its value
${varname:?message}if varname exists and isn’t null, return its value; otherwise print varname, followed by the message and abort the current command or script
${varname:+word}if varname exists and isn’t null, return word; otherwise return null
${varname:offset:length} performs substring expansion. It returns the substring of $varname starting at offset and up to length characters
${variable#pattern}if the pattern matches the beginning of the variable’s value, delete the shortest part that matches and return the rest
${variable##pattern}if the pattern matches the beginning of the variable’s value, delete the longest part that matches and return the rest
${variable%pattern}if the pattern matches the end of the variable’s value, delete the shortest part that matches and return the rest
${variable%%pattern}if the pattern matches the end of the variable’s value, delete the longest part that matches and return the rest
${variable/pattern/string}the longest match to pattern in a variable is replaced by string. Only the first match is replaced
${variable//pattern/string}the longest match to pattern in a variable is replaced by string. All matches are replaced
${#varname}returns the length of the value of the variable as a character string
*(patternlist)matches zero or more occurences of the given patterns
+(patternlist)matches one or more occurences of the given patterns
?(patternlist)matches zero or one occurence of the given patterns
@(patternlist)matches exactly one of the given patterns
!(patternlist)matches anything except one of the given patterns
$(UNIX command)command substitution: runs the command and returns standard output

# Functions.

# The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth.

# $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters.

functname() {
shell commands
}
unset -f functnamedeletes a function definition
declare -fdisplays all defined functions in your login session

# Flow Control.
statement1 && statement2and operator
statement1 || statement2or operator
-aand the operator inside a test conditional expression
-oor operator inside a test conditional expression
str1=str2str1 matches str2
str1!=str2str1 does not match str2
str1<str2str1 is less than str2
str1>str2str1 is greater than str2
-n str1str1 is not null (has length greater than 0)
-z str1str1 is null (has length 0)
-a filefile exists
-d filefile exists and is a directory
-e filefile exists; same -a
-f filefile exists and is a regular file (i.e., not a directory or other special type of file)
-r fileyou have read permission
-r filefile exists and is not empty
-w fileyou have to write permission
-x fileyou have executed permission on file, or directory search permission if it is a directory
-N filethe file was modified since it was last read
-O fileyou own file
-G filefile’s group ID matches yours (or one of yours, if you are in multiple groups)
file1 -nt file2file1 is newer than file2
file1 -ot file2file1 is older than file2
-ltless than
-le less than or equal
-eqequal
-gegreater than or equal
-gtgreater than
-nenot equal
if condition
then
statements
[elif condition
then statements...]
[else
statements]
fi
for x := 1 to 10 do
begin
    statements
end
for name [in list]
do
statements that can use $name
done
for (( initialisation ; ending condition ; update ))
do
  statements...
done
case expression in
  pattern1 )
    statements ;;
  pattern2 )
    statements ;;
  ...
esac
select name [in list]
do
  statements that can use $name
done
while condition; do
  statements
done
until condition; do
  statements
done

Bash: Input/Output Redirectors Cheat Sheet

cmd1|cmd2pipe; takes the standard output of cmd1 as standard input to cmd2
> filedirects standard output to file
< filetakes standard input from the file
>> filedirects standard output to file; append to file if it already exists
>|fileforces standard output to file even if noclobber is set
n>|fileforces output to file from file descriptor n even if noclobber is set
<> fileuses file as both standard input and standard output
n<>fileuses file as both input and output for file descriptor n
<<labelhere-document
n>filedirects file descriptor n to file
n<filetakes file descriptor n from file
n>>filedirects file description n to file; append to file if it already exists
n>&duplicates standard output to file descriptor n
n<&duplicates standard input from file descriptor n
n>&mfile descriptor n is made to be a copy of the output file descriptor
n<&mfile descriptor n is made to be a copy of the input file descriptor
&>filedirects standard output and standard error to file
<&-closes the standard input
>&-closes the standard output
n>&-closes the output from file descriptor n
n<&-closes the input from file descriptor n

Bash: Shortcuts Cheat Sheet

CTRL+Amove to the beginning of the line
CTRL+Bmoves backward one character
CTRL+Chalts the current command
CTRL+Ddeletes one character backward or logs out of the current session, similar to exit
CTRL+Emoves to the end of line
CTRL+Fmoves forward one character
CTRL+Gaborts the current editing command and ring the terminal bell
CTRL+Jsame as RETURN
CTRL+Kdeletes (kill) forward to the end of line
CTRL+Lclears the screen and redisplay the line
CTRL+Msame as RETURN
CTRL+Nnext line in the command history
CTRL+Osame as RETURN then displays the next line in a history file
CTRL+Pprevious line in the command history
CTRL+Rsearches backward
CTRL+Ssearches forward
CTRL+Ttransposes two characters
CTRL+Ukills backward from point to the beginning of the line
CTRL+Vmakes the next character typed verbatim
CTRL+Wkills the word behind the cursor
CTRL+Xlists the possible filename completion of the current word
CTRL+Yretrieves (yank) the last item killed
CTRL+Zstops the current command, resume with fg in the foreground or bg in the background
DELETEdeletes one character backward
!!repeats the last command
exitlogs out of current session