
Simple decision paths using command-line lists
We have used command-line lists both in in some of the scripts found in statements that we can create and so we thought that it was appropriate to use them in the earlier examples before fully explaining them here.
Command-line lists are two or more statements that are joined using either the AND
or OR
notations:
&&
:AND
||
:OR
Where the two statements are joined using the AND
notation, the second command only runs if the first command succeeds. Whereas, with the OR
notation the second command will run only if the first command fails.
The decision of the success or failure of a command is taken by reading the exit code from the application. A zero represents a successful application completion and anything other than a zero will represent a failure. We can test the success or failure of an application by reading the exit status by means of the system variables $?
. This is shown in the following example:
$ echo $?
If we need to ensure that a script is run from a user's home directory, we can build this into the script's logic. This can be tested from the command line and it does not have to be in a script. Consider the following command-line example:
$ test $PWD == $HOME || cd $HOME
The double vertical bars denote an OR
list. This ensures that the second statement is only executed when the first statement is not true. In simple terms, if we are not currently in the home directory we will be by the end of the command-line list. We will see more on the test command soon.
We can build this into almost any command that we want and not just test. For example, we can query to see if a user is logged into the system, if they are then we can use the write
command to directly message their console. Similar as before, we can test this in the command line prior to adding it to the script. This is shown in the following command-line example:
$ who | grep pi > /dev/null 2>&1 && write pi < message.txt
If we use this in a script, it is almost certain that we will replace the username with a variable. In general, if we have to refer to the same value more than once then a variable is a good idea. In this case, we are searching for the pi
user.
When we break the command-line list down, we first use the who
command to list the users who are logged on. We pipe the list to grep
to search for the desired username. We are not interested in the output from the search, just the success or failure. With this in mind, we redirect all our output to /dev/null
. The double ampersand indicates that the second statement in the list runs only if the first returns true. If the pi
user is logged on, we use write
to message the user. The following screenshot illustrates this command and the output.
