More on Operators
Explore how to use logical AND (&&) and OR (||) operators in Bash to execute commands conditionally. Understand short-circuit evaluation and how to log success or error messages based on command results.
We'll cover the following...
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 && ...