<aside>
💡 Like in many other languages, Bash has conditions to easily behave differently given a certain condition. The conditions in Bash are the if/else
clause and a case
. Indentation is important when writing your clauses multiline and when writing single line clauses, they need to be delimited by a semicolon.
</aside>
You denote that this clause ends by typing fi
. Be sure to place a semicolon after the assertion, followed by then
to create a correct clause. A simple if/else clause can be formed by asserting a condition and performing the command if the condition resolves truthy:
if grep "Detail" ouput.log; then
echo "Contains Detail in ouput.log"
else
echo "No Detail in output.log"
return 1
fi
In the examples above only commands are being used to assert a condition. If you remember expressions from 1. What is Bash they will come in handy here. Since expressions are evaluated inline they can easily be used in an if/else clause:
if [[ -f index.js ]]; then
cat index.js
else
echo "No index.js file"
fi
# You could also write the above as shorthand:
if [[ -f index.js ]]; then cat index.js; else echo "No index.js file"; fi
Cases can be used to assert a lot of conditions at once, not having to write a tedious repeated elif. The syntax for cases is somewhat difficult, there is:
*)
catch-all case which is used as a default when no other cases match;;
to break out of a case. Always break out of a case or you're in for trouble, since cases cascadecase "$OPTIONS" in
"force")
echo "Force option is enabled."
run_main_pipeline "FORCE"
;;
"debug")
echo "Debug mode enabled."
run_main_pipeline "DEBUG"
;;
"dry-run")
echo "Doing a dry run"
exit 0
;;
*)
echo "No options enabled."
run_main_pipeline
;;
esac