Bash and Scripting

Basics

Use the following to define the interpreter to be used by the shell script (bash in our case):
1
#!/bin/bash
Copied!
Arguments variables that are passed to the script. These are also called parameters $0 - the name of the script $1 - first parameter from the script $2 - second parameter from the script and so on

Example Script

See the example script below - script checks the IP with a ping command:
1
#!/bin/bash
2
​
3
$ip=`route -n | grep UG | tr -s " " | cut -f 2 -d " "`
4
​
5
$ping="/bin/ping"
6
​
7
echo "Checking to se if $ip address is up..."
8
​
9
$ping -c 5 $ip
Copied!

If Statements*

1
if [ <condition> ]
2
then
3
<command>
4
fi
Copied!
See the list of available conditions below: ![expression] - the expression is false -n [string] - the length of the string is greater than zero -z [string] - the length of the string is zero string1 = string2 - string is equal to sting2 string1 != string2 - string is not equal to sting2 integer1 -eq integer2 - integer1 is equal integer2 integer1 -gt integer2 - integer1 is greater than integer2 integer1 -lt integer2 - integer1 is less than integer2 -d [file] - the file exists and is a directory -e [file] - the file exists -r [file] - the file exists, and the read permission is granted -s [file] - the file exists, and its size is greater than zero -w [file] - the file exists, and the write permission is granted -x [file] - the file exists, and the execute permission is granted * This section was copied from the Linux Academy course: LPI Linux Essentials Certification created by Michael Christian -- you can find it here.

For Loops

1
for i in list;
2
do <command>;
3
done
Copied!
​

While Loops

1
while [condition]; do
2
<command>
3
done
Copied!

​

Case Statements

1
case [expression] in
2
PATTERN_1)
3
STATEMENTS
4
;;
5
​
6
PATTERN_2)
7
STATEMENTS
8
;;
9
​
10
PATTERN_N)
11
STATEMENTS
12
;;
13
​
14
*)
15
echo -n "unknown"
16
;;
17
esac
Copied!
​
​