CyberAces Module3-Bash 3 FlowControl
CyberAces Module3-Bash 3 FlowControl
But this processes each word separated by spaces in the output. If you want to parse
an entire line, you can use the while loop with the "read" command, which will assign
a full line to a variable as demonstrated in the second script above.
You can run several commands on the same line by separating them with a semicolon
(";"). For example:
$ cd ~; ls -la ; cd /var/log; cat messages
This would change to your home directory, list the files, change to the "/var/log"
directory and print the contents of the "messages" file to the screen.
As mentioned earlier, conditional operators can also be used between commands on
the command line. With "&&", the second command will only be run if the first
command succeeds, and with "||" the second command will only be run if the first
command fails. For example, the following line will print an error if there is a problem
reading the "messages" log:
$ cat /var/log/messages || echo "Error reading messages"
This functionality is due to the "short-circuit" nature of Linux logic. For example, with
the Logical AND the result will be False if any of the input is False, so it will stop
evaluating input once it reaches the first False result. Similarly, a Logical OR will return
True if any input evaluates to True. Once it encounters the first True input it can stop
evaluating the inputs.
$ echo test write > /etc/testfile && rm /etc/testfile &&
echo Everything Worked
This command has three parts and each piece will execute if the previous was
successful. If the creation of /etc/testfile works then, and only then, will the file be
deleted. Only if the deletion was successful (the first command would have to have
been successful as well), would the words "Everything Worked" be output.
Congratulations! You have completed the session on flow control in Bash.
In the next session, we will discuss parsing and searching using Bash.