BASH: &&,|| instead of if/else
In bash you can beautify your code by using logical operators instead of if/else statements:
A && B : If A is executed successfully then B is executed
A || B : If A fails, then B is executed
A; B : B is executed regardless of whether A was successful or not.
Simple example:
cat the file if it exists, and if not echo an error message:
If/else
if [ -e file.txt ]; then cat file.txt else echo "file.txt doesn't exist" exit 1; fi exit 0;
logical operators
cat file.txt 2>/dev/null || { echo "file.txt doesn't exist"; exit 1; }; exit 0
Notice that I put 2>/dev/null to redirect error output to the null device so the error is not shown in case it exists. Also, since the right part of the || has multiple commands, it is contained in curly brackets
















