Hi folks, this article is meant to be a really short introduction to Bash.
First, what is Bash? Bash is a Unix shell and command language developed by Brian Fox for the GNU Project as a free software replacement for the Bourne shell [1]. Bash is the default shell on most Linux and macOS systems. Bash has even been ported to Windows as it is supported natively in Windows 10 and through Cygwin and MinGW. A Bash script is a file containing one or commands and can be very useful to automate commands that you may otherwise have to type out yourself each time on a terminal. Without further ado, let’s dive in.
Interpreter Directive
A common way to write Bash scripts is to add an interpreter directive as the first line of the file, e.g.
#!/bin/bash
This way, once the file is made executable, a user can execute the file directly from a terminal and it will be executed with Bash automatically.
Variable assignment
Variable assignment is done as follows:
x="some tuff"
Note that there shouldn’t be space between the letter and the = sign.
Referencing variables
y=$x
E.g.
x=5 y=$x echo y is $y
If conditions
Here is an example of how to write an if statement.
if [ $x == "some stuff" ] then echo some stuff fi
If/else conditional statement
if [ $x == "stuff" ] then echo some stuff else echo some other stuff fi
If/else if/else clause
if [ $x == "foo" ] then echo some stuff elif [ $x == "bar" ] then echo some other stuff else echo the last stuff fi
Arrays
myArray=(1 2 3)
While Loop Through an Array
myArray=(1 2 3) count=0 while [ "x${myArray[count]}" != "x" ] do echo element is ${myArray[count]} count=$(( $count + 1 )) done
You can find much more details in Mike G’s excellent BASH Programming website [2].
References
1. Bash (Unix shell) – Wikipedia. view-source:https://en.wikipedia.org/wiki/Bash_(Unix_shell) [16/02/17].
2. BASH Programming – Introduction HOW-TO. http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html [16/02/17].