Scripting with BASH#
Most Linux distributions come with the bash shell. It is a very simple shell, but it is also a very powerful one. It is an updated version of the Bourne shell, which is the most common shell on UNIX systems. As a result, it is the most commonly used shell on UNIX systems and knowning how to script in the bash shell is a prerequisite to use Linux as a power user on any system.
Variables#
Variables in shells are strings that are assigned to a name. The name is followed by an equals sign, and then the value of the variable. The value can be a string, a number, or a special value.
1#!/bin/bash
2
3i=0
4echo $i
Command substitution#
Assinging a value to a variable can also be done by command substitution where the output of a command is assigned to a variable.
1#!/bin/bash
2
3i=`date +%s`
4echo $i
Exit-codes#
`$?`
Conditional structures#
If-then-else#
Conditional structures are used to evaluate a condition and execute a command if the condition is true. Based on this a command is executed if the condition is true or another if the condition is false.
1#!/bin/bash
2
3i=1
4if [ $i -eq 1 ]
5then
6 echo "i equals 1"
7else
8 echo "i does not equal 1"
9fi
The if-then-else construct can also be extended to include an else-if statement.
1#!/bin/bash
2
3i=1
4j=2
5if [ $i -eq 1 ]
6then
7 echo "i equals 1"
8elif [ $j -eq 2 ]
9then
10 echo "j equals 2"
11else
12 echo "i and j do not equal 1 or 2"
13fi
Short-circuit evaluation#
The shell also allows to write short form conditional statements. This is can be used by using /usr/bin/[
or [
as the first character of the condition. It is an alternative to the test
command and with the &&
and ||
operators the action can be defined.
1#!/bin/bash
2
3i=1
4[ $i -eq 1 ] && echo "i equals 1"
Case statement#
Beside the if-then-else construct, the shell also allows to define a case statement. This is used to evaluate a value and execute a command based on the value. This makes the script more flexible and can be used to evaluate multiple values.
1#!/bin/bash
2
3i=1
4
5case $i in
6 1) echo "One";;
7 2) echo "Two";;
8 3) echo "Three";;
9 *) echo "Unknown";;
10esac
Loops#
For loops#
Iterating over a list of values is done by using a for loop. The for loop is used to iterate over a list of values. The for loop is defined by the keyword for
, followed by the name of the variable, followed by the keyword in
, followed by the list of values. The list of values is separated by a space.
1#!/bin/bash
2
3for i in {1..10}
4do
5 echo $i
6done
While loops#
Counter based loops are used to iterate over a list of values. The while loop is defined by the keyword while
, followed by the condition, followed by the keyword do
, followed by the commands, followed by the keyword done
.
1#!/bin/bash
2
3while :
4do
5 echo "Hello World!"
6 sleep 1
7done
1#!/bin/bash
2
3while :; do
4 echo "Hello World!"
5 sleep 1
6done