cheatsheet

Example

1
#!/bin/bash
2
3
NAME="Payam"
4
echo "Hello $NAME!"
5
6
exit 0
Copied!

Variables:

1
varname=value # defines a variable
2
varname=value command # defines a variable to be in the environment of a particular subprocess
3
echo $varname # checks a variable's value
4
read <varname> # reads a string from the input and assigns it to a variable
5
let <varname> = <equation> # performs mathematical calculation using operators like +, -, *, /, %
6
export VARNAME=value # defines an environment variable (will be available in subprocesses)
Copied!
1
#Special shell variables
2
echo $ # prints process ID of the current shell
3
echo $! # prints process ID of the most recently invoked background job
4
echo $? # displays the exit status of the last command
5
echo $0 # display Filename of the shell script
Copied!

Quoting:

1
\c #Take character c literally.
2
`cmd` #Run cmd and replace it in the line of code with its output.
3
"whatever" #Take whatever literally, after first interpreting $, `...`, \
4
'whatever' #Take whatever absolutely literally.
5
6
#Example:
7
match=`ls *.bak` #Puts names of .bak files into shell variable match.
8
echo \* #Echos * to screen, not all filename as in: echo *
9
echo '$1$2hello' #Writes literally $1$2hello on screen.
10
echo "$1$2hello" #Writes value of parameters 1 and 2 and string hello.
Copied!

Redirection

1
python hello.py > output.txt # stdout to (file)
2
python hello.py >> output.txt # stdout to (file), append
3
python hello.py 2> error.log # stderr to (file)
4
python hello.py 2>&1 # stderr to stdout
5
python hello.py 2>/dev/null # stderr to (null)
6
python hello.py &>/dev/null # stdout and stderr to (null)
7
python hello.py < foo.txt # feed foo.txt to stdin for python
Copied!

Brace expansion

1
{A,B} Same as A B
2
{A,B}.js Same as A.js B.js
3
{1..5} Same as 1 2 3 4 5
Copied!

Parameter expansions

Basics

1
name="John"
2
echo ${name}
3
echo ${name/J/j} #=> "john" (substitution)
4
echo ${name:0:2} #=> "Jo" (slicing)
5
echo ${name::2} #=> "Jo" (slicing)
6
echo ${name::-1} #=> "Joh" (slicing)
7
echo ${name:(-1)} #=> "n" (slicing from right)
8
echo ${name:(-2):1} #=> "h" (slicing from right)
9
echo ${food:-Cake} #=> $food or "Cake"
10
11
length=2
12
echo ${name:0:length} #=> "Jo"
Copied!
1
STR="/path/to/foo.cpp"
2
echo ${STR%.cpp} # /path/to/foo
3
echo ${STR%.cpp}.o # /path/to/foo.o
4
echo ${STR%/*} # /path/to
5
6
echo ${STR##*.} # cpp (extension)
7
echo ${STR##*/} # foo.cpp (basepath)
8
9
echo ${STR#*/} # path/to/foo.cpp
10
echo ${STR##*/} # foo.cpp
11
12
echo ${STR/foo/bar} # /path/to/bar.cpp
13
STR="Hello world"
14
echo ${STR:6:5} # "world"
15
echo ${STR: -5:5} # "world"
16
SRC="/path/to/foo.cpp"
17
BASE=${SRC##*/} #=> "foo.cpp" (basepath)
18
DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
Copied!

Substitution

1
${FOO%suffix} Remove suffix
2
${FOO#prefix} Remove prefix
3
${FOO%%suffix} Remove long suffix
4
${FOO##prefix} Remove long prefix
5
${FOO/from/to} Replace first match
6
${FOO//from/to} Replace all
7
${FOO/%from/to} Replace suffix
8
${FOO/#from/to} Replace prefix
Copied!

Length

1
${#FOO} Length of $FOO
Copied!

Default Values

1
${FOO:-val} $FOO, or val if unset (or null)
2
${FOO:=val} Set $FOO to val if unset (or null)
3
${FOO:+val} val if $FOO is set (and not null)
4
${FOO:?message} Show error message and exit if $FOO is unset (or null)
5
6
#Omitting the : removes the (non)nullity checks,
7
#e.g. ${FOO-val} expands to val if unset otherwise $FOO.
Copied!

Comment

1
# Single line comment
2
: '
3
This is a
4
multi line
5
comment
6
'
Copied!

Substrings

1
${FOO:0:3} Substring (position, length)
2
${FOO:(-3):3} Substring from the right
Copied!

Manipulations

1
STR="HELLO WORLD!"
2
echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)
3
echo ${STR,,} #=> "hello world!" (all lowercase)
4
5
STR="hello world!"
6
echo ${STR^} #=> "Hello world!" (uppercase 1st letter)
7
echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)
Copied!

Conditionals:

Test Operators

In Bash, the test command takes one of the following syntax forms:
    test EXPRESSION
    [ EXPRESSION ]
    [[ EXPRESSION ]]
To make the script portable, prefer using the old test [ command which is available on all POSIX shells. The new upgraded version of the test command [[ (double brackets) is supported on most modern systems using Bash, Zsh, and Ksh as a default shell. To negate the test expression, use the logical NOT (!) operator.

Checking Numbers

Note that a shell variable could contain a string that represents a number. If you want to check the numerical value use one of the following:
1
[[ NUM -eq NUM ]] Equal
2
[[ NUM -ne NUM ]] Not equal
3
[[ NUM -lt NUM ]] Less than
4
[[ NUM -le NUM ]] Less than or equal
5
[[ NUM -gt NUM ]] Greater than
6
[[ NUM -ge NUM ]] Greater than or equal
Copied!

Checking Strings

1
[[ -z STRING ]] Empty string
2
[[ -n STRING ]] Not empty string
3
[[ STRING == STRING ]] Equal
4
[[ STRING != STRING ]] Not Equal
5
Copied!

Checking files

1
[[ -e FILE ]] Exists
2
[[ -r FILE ]] Readable
3
[[ -h FILE ]] Symlink
4
[[ -d FILE ]] Directory
5
[[ -w FILE ]] Writable
6
[[ -s FILE ]] Size is > 0 bytes
7
[[ -f FILE ]] File
8
[[ -x FILE ]] Executable
9
[[ FILE1 -nt FILE2 ]] 1 is more recent than 2
10
[[ FILE1 -ot FILE2 ]] 2 is more recent than 1
11
[[ FILE1 -ef FILE2 ]] Same files
Copied!

More conditions:

1
[[ -o noclobber ]] If OPTIONNAME is enabled
2
[[ ! EXPR ]] Not
3
[[ X && Y ]] And
4
[[ X || Y ]] Or
Copied!

if statement:

1
#if Statement
2
3
echo -n "Enter a number: "
4
read VAR
5
6
if [[ $VAR -gt 10 ]]
7
then
8
echo "The variable is greater than 10."
9
fi
Copied!
1
#if..else Statement
2
3
echo -n "Enter a number: "
4
read VAR
5
6
if [[ $VAR -gt 10 ]]
7
then
8
echo "The variable is greater than 10."
9
else
10
echo "The variable is equal or less than 10."
11
fi
Copied!
1
#if..elif..else Statement
2
3
echo -n "Enter a number: "
4
read VAR
5
6
if [[ $VAR -gt 10 ]]
7
then
8
echo "The variable is greater than 10."
9
elif [[ $VAR -eq 10 ]]
10
then
11
echo "The variable is equal to 10."
12
else
13
echo "The variable is less than 10."
14
fi
Copied!
1
# Nested if Statements
2
echo -n "Enter the first number: "
3
read VAR1
4
echo -n "Enter the second number: "
5
read VAR2
6
echo -n "Enter the third number: "
7
read VAR3
8
9
if [[ $VAR1 -ge $VAR2 ]]
10
then
11
if [[ $VAR1 -ge $VAR3 ]]
12
then
13
echo "$VAR1 is the largest number."
14
else
15
echo "$VAR3 is the largest number."
16
fi
17
else
18
if [[ $VAR2 -ge $VAR3 ]]
19
then
20
echo "$VAR2 is the largest number."
21
else
22
echo "$VAR3 is the largest number."
23
fi
24
fi
Copied!

Loops:

for:

1
#basic for loop
2
for i in 1 2 3 4 5
3
do
4
echo "Welcome $i times"
5
done
Copied!
1
#Basic for loop
2
for i in /etc/rc.*; do
3
echo $i
4
done
Copied!
1
#Ranges
2
for i in {1..5}; do
3
echo "Welcome $i"
4
done
Copied!
1
#C-Like for loop
2
for ((i = 0 ; i < 100 ; i++)); do
3
echo $i
4
done
Copied!
1
#with step size
2
for i in {5..50..5}; do
3
echo "Welcome $i"
4
done
Copied!

while:

1
n=1
2
3
while [ $n -le 5 ]
4
do
5
echo "Welcome $n times."
6
n=$(( n+1 ))
7
done
Copied!
1
#Using ((expression)) Format With The While Loop
2
n=1
3
while (( $n <= 5 ))
4
do
5
echo "Welcome $n times."
6
n=$(( n+1 ))
7
done
Copied!
1
#for ever
2
while true; do
3
···
4
done
Copied!
1
# Reading a test file:
2
###example1/2:
3
cat /etc/resolv.conf | while read line; do
4
echo $line
5
done
6
7
###example2/2:
8
file=/etc/resolv.conf
9
while IFS= read -r line
10
do
11
echo $line
12
done < "$file"
13
14
### Reading A Text File With Separate Fields:
15
file=/etc/resolv.conf
16
# set field separator to a single white space
17
while IFS=' ' read -r f1 f2
18
do
19
echo "field # 1 : $f1 ==> field #2 : $f2"
20
done < "$file"
Copied!

Until:

1
#!/bin/bash
2
3
counter=0
4
5
until [ $counter -gt 5 ]
6
do
7
echo Counter: $counter
8
((counter++))
9
done
Copied!

Case:

1
Case/switch
2
case "$1" in
3
start | up)
4
vagrant up
5
;;
6
7
*)
8
echo "Usage: $0 {start|stop|ssh}"
9
;;
10
esac
Copied!

Functions:

1
# Defining functions:
2
myfunc() {
3
echo "hello $1"
4
}
5
# Same as above (alternate syntax)
6
function myfunc() {
7
echo "hello $1"
8
}
9
myfunc "John"
Copied!
1
#Returning values:
2
myfunc() {
3
local myresult='some value'
4
echo $myresult
5
}
6
result="$(myfunc)"
Copied!
1
#Raising errors:
2
myfunc() {
3
return 1
4
}
5
if myfunc; then
6
echo "success"
7
else
8
echo "failure"
9
fi
Copied!
1
#Arguments:
2
$# Number of arguments
3
$* All arguments
4
[email protected] All arguments, starting from first
5
$1 First argument
6
$_ Last argument of the previous command
Copied!

Arrays

1
Defining arrays
2
Fruits=('Apple' 'Banana' 'Orange')
3
Fruits[0]="Apple"
4
Fruits[1]="Banana"
5
Fruits[2]="Orange"
Copied!
1
Operations
2
Fruits=("${Fruits[@]}" "Watermelon") # Push
3
Fruits+=('Watermelon') # Also Push
4
Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
5
unset Fruits[2] # Remove one item
6
Fruits=("${Fruits[@]}") # Duplicate
7
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
8
lines=(`cat "logfile"`) # Read from file
Copied!
1
Working with arrays
2
echo ${Fruits[0]} # Element #0
3
echo ${Fruits[-1]} # Last element
4
echo ${Fruits[@]} # All elements, space-separated
5
echo ${#Fruits[@]} # Number of elements
6
echo ${#Fruits} # String length of the 1st element
7
echo ${#Fruits[3]} # String length of the Nth element
8
echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
9
echo ${!Fruits[@]} # Keys of all elements, space-separated
Copied!
1
Iteration
2
for i in "${arrayName[@]}"; do
3
echo $i
4
done
Copied!

Dictionaries:

1
Defining
2
declare -A sounds
3
sounds[dog]="bark"
4
sounds[cow]="moo"
5
sounds[bird]="tweet"
6
sounds[wolf]="howl"
Copied!
1
Working with dictionaries
2
echo ${sounds[dog]} # Dog's sound
3
echo ${sounds[@]} # All values
4
echo ${!sounds[@]} # All keys
5
echo ${#sounds[@]} # Number of elements
6
unset sounds[dog] # Delete dog
Copied!
1
Iteration
2
Iterate over values
3
for val in "${sounds[@]}"; do
4
echo $val
5
done
6
Iterate over keys
7
for key in "${!sounds[@]}"; do
8
echo $key
9
done
Copied!

Debugging

1
bash -n scriptname # don't run commands; check for syntax errors only
2
set -o noexec # alternative (set option in script)
3
4
bash -v scriptname # echo commands before running them
5
set -o verbose # alternative (set option in script)
6
7
bash -x scriptname # echo commands after command-line processing
8
set -o xtrace # alternative (set option in script)
Copied!

Miscellaneous:

1
#Numeric calculations
2
$((a + 200)) # Add 200 to $a
3
$(($RANDOM%200)) # Random number 0..199
Copied!
1
#Inspecting commands
2
command -V cd
3
#=> "cd is a function/alias/whatever"
Copied!
1
#Heredoc:
2
cat <<END
3
hello world
4
END
Copied!
1
#printf:
2
printf "Hello %s, I'm %s" Sven Olga
3
#=> "Hello Sven, I'm Olga
4
5
printf "1 + 1 = %d" 2
6
#=> "1 + 1 = 2"
7
8
printf "This is how you print a float: %f" 2
9
#=> "This is how you print a float: 2.000000"
Copied!
1
#Reading input
2
echo -n "Proceed? [y/n]: "
3
read ans
4
echo $ans
5
6
#Reading Just one character:
7
read -n 1 ans
Copied!
1
#Getting options
2
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
3
-V | --version )
4
echo $version
5
exit
6
;;
7
-s | --string )
8
shift; string=$1
9
;;
10
-f | --flag )
11
flag=1
12
;;
13
esac; shift; done
14
if [[ "$1" == '--' ]]; then shift; fi
Copied!
1
#Check for command’s result
2
if ping -c 1 google.com; then
3
echo "It appears you have a working internet connection"
4
fi
Copied!
Payam Borosan.Goodluck
Last modified 1yr ago