We have used command-line lists (|| and &&), both in Chapter 1, The What and Why of Scripting with Bash, and in some of the scripts found in Chapter 2, Creating Interactive Scripts. Lists are one of the simplest conditional 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 on 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 represents 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 Boolean. 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, and if they are, then we can use the write command to directly message their console. Similar to 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
Note that you should change the user pi to your username.
If we use this in a script, it is almost certain that we will replace the username with a variable. In general, if we need to refer to the same value more than once, then using 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 its success or failure. Bearing 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: