Logical Operator AND
Learn how to use the logical AND operator in your Bash commands.
We'll cover the following
Conditional algorithm
The pipeline allows us to combine several commands. These commands together make an algorithm with a linear sequence. The computer executes actions of such an algorithm, one by one, without any conditions.
Let’s suppose we need a more complex algorithm. There, the result of the first command determines the next step. The computer does one action if the command succeeds. Otherwise, it does another action. Such a dependency is known as a conditional algorithm. The pipeline does not fit in this case.
We’ll go over an example of the conditional algorithm. We want to write a command to copy the directory. If this operation succeeds, the command writes the “OK” line in the log file. Otherwise, it writes the “Error” line there.
We can write the following command using the pipeline
cp -R ~/docs ~/docs-backup | echo "OK" > result.log
This command does not work properly. It writes the “OK” line to the result.log
file, regardless of the copying result. Even if the docs
directory does not exist, the log file is generated and we get the “OK” line. The log file reports that the operation succeeded, but in fact it failed.
The cp
utility result should define the echo
output. We can get this behavior using the &&
operator. Then, the command becomes like this:
cp -R ~/docs ~/docs-backup && echo "OK" > result.log
Now, echo
prints the “OK” line when the cp
utility succeeds. Otherwise, there is no output to the log file. We can read the result by running cat result.log
.
Run the commands discussed in this lesson in the terminal below.
Get hands-on with 1400+ tech skills courses.