Introduction
This is a simple bash script cheatsheet.
Variables
Define variables
1
2
3
abc = 123
hello = 321
qwerty = asdf
Assign output of command to variable
Argument
Argument and default value
1
2
words = ${ 1 -hello } # If variable not set or null, use default.
FOO = ${ VARIABLE :=default } # If variable not set or null, set it to default.
Ensure no spaces between variable name and value
View variable content
1
2
3
4
5
6
$ echo $abc
# outputs: 123
$ echo " $( echo "upg" ) "
# outputs: upg
$ echo '$(echo "upg")'
# outputs: $(echo "upg")
Loops
For loop
1
2
3
4
for i in { 1..5}
do
echo "Hello $i "
done
{START..END..INCREMENT}
1
2
3
4
for i in { 0..10..2}
do
echo "Hello $i "
done
Files
1
2
3
4
for file in $HOME
do
echo $file
done
While loop
1
2
3
4
while [ condition ]
do
echo "hello"
done
Infinite while loop
1
2
3
4
while true
do
echo "hello"
done
Hit CTRL-C to stop the loop
Read File
1
2
3
4
5
6
7
8
#!/usr/bin/env bash
FILE = ${ 1 -hello.txt }
while read line
do
# use $line variable to process line
echo $line
done < " $FILE "
If Else Loop
1
2
3
4
5
6
7
if [ condition ] ; then
echo 1
elif [ condition2 ] ; then
echo 2
else
echo 3
fi
Conditions
Operator
Description
-eq
Equal
-lt
Less than
-le
Less than or equal to
-gt
Greater than
-ge
Greater than or equal to
==
2 Strings equal
!=
2 Strings not equal
!
Statement is false
-d
Directory is present
-e
File is present
-f
File is present
-z “$1” *
Check for empty argument
* Note the space between the operator and argument
Condition Usage Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if [[ " $1 " == "bash" && " $2 " = "shell" ]] ; then
echo " $1 $2 "
elif [ " $1 " == "bash" ] ; then
echo " $1 "
elif [ -e " $HOME /hello.txt" ]
echo "File Present"
elif [ ! -d " $HOME /Documents" ]
echo "Directory NOT Present"
else
echo Condition
fi
Case
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
word = $1
case " $word " in
hello)
echo hello
;;
bye)
echo bye
;;
*)
echo Universal
;;
esac
Functions
1
2
3
function fun(){
echo fun
}
String Manipulation
Concatenate Strings
1
2
3
4
string1 = abc
string2 = def
echo " $string1$string2ghi jkl"
# Outputs: abcdefghi jkl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string = "hello/devoalda/devo.com"
# Get Filename
echo ${ string ##*/ }
# Outputs: devo.com
# Get Path
echo ${ string %/* }
# Outputs: hello/devoalda
# Get File Extension
echo ${ string ##*. }
# Outputs: com
# Multiple Operations
NAME = ${ string ##*/ } # remove part before last slash
echo ${ NAME %.* } # from the new var remove the part after the last period
# Outputs: devo
String contain substring
bash
python
bash
1
2
3
4
5
6
7
8
echo "This is a bash script" | grep "bash"
# True if "bash" is in sentence
test = 'GNU/Linux is an operating system'
if [[ $test == *"Linux" * ]] ; then
echo "true"
fi
python
1
2
3
4
5
test = 'GNU/Linux is an operating system'
if "Linux" in test :
print ( 'true' )
else :
print ( 'false' )