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:
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
VARIABLE1='hello world' if [[ $VARIABLE1 == 'hello world' ]] then echo 'Hello World!' fi
In this example we see:
- Variable $VARIABLE1 is set to the value
- The content of $VARIABLE1 is matched against the string
- If this is true, then print
Hello World!to the screen.
Several kinds of loops can created in bash:
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
done for each name. This will output all 5 names seperated 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 seperated by newline.
VARIABLE1=1 while [ $VARIABLE1 -lt 10 ] do echo "$VARIABLE1" VARIABLE1=$[$VARIABLE1+1] done