5 Things to know before starting scripting in Bash Shell
Don’t make the same mistakes than me!
#1 Command Lifecycle
When a command is given to the shell, the interpreter does the following main steps:
- Variable substitution — replaces all variables with their values
- Line parsing — the interpreter re-scans again the line and trims additional spaces between arguments+ parses special chars
- Command execution — Executes given command
For an example, what you think it would be the output of the script bellow?
Let’s have a look why:
- First the shell replaces the $ahah variable with it’s initial value
- Then, it re-scans the line and because the value of $ahah is not quoted, it trims all the additional spaces (resulting in “Several spaces *”) and finally it parses the special char “*”, that in this case, lists all the files of the current directory, separated by a space
- Finally echo is executed with the following arguments: “Several”, “spaces”, “lifecycle.sh” and “phones.txt”
#2 Every variable is a string!
In Bash every variable is treated as a string! That’s why the following script outputs “Not Equal”:
To compare two integers we have to use specific options like -eq:
PS: For integer operations, such as addition, subtraction, multiplication or division you should use expr or $(())
#3 [ is a command
A funny fact about the Bash is that [ is an actual command. Test this out:
The [ command is basically the test command but it also requires a closing tag ].
Note: That’s why spaces between the [ and ] are so important, because they separate the command arguments! Otherwise the [ command will not properly recognise its arguments
#4 Don’t loop over $*
Looping over $* almost always means bug! Check what happens when the argument given has spaces (second run):
And this is not solved by adding double quotes:
What we commonly expected is to loop over “$@” (double quotes included), like:
#5 Use -x option for debugging
We all know that traditional echo commands can be handy for debugging, but most of the times the -x option can make things easier! Take a look of what happens when we enable this option:
For more about the Bash Shell you could read the book Shell Programming in Unix, Linux and OS X from Stephen G. Kochan and Patrick Wood