More on Operators
Learn how to use the logical OR operator in your Bash commands.
We'll cover the following
We are writing a command to copy the directory. If this operation succeeds, the command should write the “OK” line in the log file. Otherwise, it should write the “Error” line there.
The following command prints the “OK” line in the log file when copying succeeds.
cp -R ~/docs ~/docs-backup && echo "OK" > result.log
Using logical OR
Now, we need to handle the case of a failure. If copying fails, the log file should get the “Error” line. We can add this behavior with the || operator, which does logical OR.
When adding the OR operator (||
), our command looks like this:
cp -R ~/docs ~/docs-backup && echo "OK" > result.log || echo "Error" > result.log
The following figure shows the scenario where our command listed above fails if the folder ~/docs
does not exist.
Get hands-on with 1200+ tech skills courses.