Search⌘ K

Logical Operator AND

Explore how to use the logical AND operator && in Bash to create conditional command sequences. Understand exit codes, short-circuit evaluation, and how to log outcomes based on command success or failure. Gain hands-on skills for writing effective conditional 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 ...