Simple Logic with BASH Command Line Lists
We can simplify our logic and coding by making use of BASH command line lists. This does create simple logic but may effect the readability of your code so use wisely. As the name suggests bash command line lists are lists of commands that run on the success or failure of other commands. Using the example in the graphic that we have here we first test to see if the script’s first argument is a file; if it is not then we exit with error code 1. We use the || to represent that code should run on left condition returning false . Using && we specify that the code on the right should run only if the code on the left returns true.
If we move through to our home directory using:
Remember cd on its own will take us to our home directory. Now of course we know we are in the home directory but we can see how to test this from within a script.
[ $PWD == $HOME ] && echo "We are home"
First we test to see if the variable $PWD ( your current directory ) is equal to your home directory, if it is we print a message. If we move from this directory and run the code again we will not see the message.
We could also reverse the code:
[ $PWD == $HOME ] || echo "We are not home"
So now we run the echo command only if the first command returns false. So the message will print if we are not in our home directory.
For the example script we use to demonstrate BASH command line lists we see a very sparse scripts:
#!/bin/bash [ $# -eq 1 ] || exit 1 #ensure we have exactly 1 argument [ -f $1 ] || exit 2 #ensure that the argument is a regular file wc -l $1 # count the number of lines in the file argument
We start by testing the number of arguments supplied to the script. We can read the argument count using the variable $#. We check that the count is exactly 1, if it is true we don’t run the command to the right of the test which exits the script.
Next we check that the argument provided is a regular file, if it is not then we run the exit code again. Only after both of these tests have succeeded can we run the 3rd line of code to count the number of lines in the file.
The video follows:
My Book on Shell Scripting is available from good book shops and the publisher Packt.