Bash scripting is making scripts in the Bash shell language.
Bash has several features which allow making small uncompiled programs (scripts) to automate functionality. It features basic programming constructs like variables, IF-statements and loops.
Bash scripts are usually created in files with the .sh extension. To make the file executable as it were a program, put the following line at the top of the file:
#!/bin/bash
This will instruct the kernel to start a Bash shell and use the rest of the file as input. After adding the 'shebang' line, change the permissions of the file to be executable with chmod +x filename.sh. You can then run the script with ./filename.sh.
Example IF-statement
VARIABLE1='hello world'
if [[ $VARIABLE1 == 'hello world' ]]
then
echo 'Hello World!'
fi
In this example we see:
- Variable $VARIABLE1 is set to the value
hello world - The content of $VARIABLE1 is matched against the string
hello world - If this is true, then print
Hello World!to the screen.
Example Loop
Several kinds of loops can created in bash:
For loop
VARIABLE1="anna bob charlie dave eve"
for NAME in $VARIABLE1
do
echo $NAME
done
The for statement will iterate through the names in $VARIABLE1 and run the code block between do and done for each name. This will output all 5 names separated by newlines.
You can also create a C-style for-loop:
for ((i = 0 ; i < 10 ; i++)); do
echo $i
done
This will print numbers 1 through 9 separated by newlines.
While loop
VARIABLE1=1
while [ $VARIABLE1 -lt 10 ]
do
echo "$VARIABLE1"
VARIABLE1=$[$VARIABLE1+1]
done