Bash Script Note 1
Writing robust scripts
We should use the following options in our bash script for better quality:
set -eux set -o pipefail
Meaning of these option:
-e: Exit immediately if a command fails.
-u: If a variable is not set, this is considered an error1.
-x: Expand variables in a command and print it before executing the command (better for debugging if command fails).
-o pipefail: If any command in a pipe fails, this pipe will fail.
For more options, see bash set command doc.
common check conditions for files
Some commonly used options for checking file conditions:
|True if FILE exists and is a directory|
|True if FILE exists and is a regular file|
|True if FILE exists and is readable|
|True if FILE exists and is writable|
|True if FILE exists and is executable|
|True if length of STRING is zero|
|True if length of STRING is not zero|
Note that to check if the opposite is true, use
[ ! condition ].
[ ] or
[[ ]] for condition check?
[ ] and
[[ ]] can be used to check some conditions, but
[ ] is POSIX
[[ ]] is not. Both bash, zsh support
[[ ]] is also more versatile and powerful than
[ ]. For example, it
|| and grouping command using
Compare string equality
We can use
!= to compare the equality of strings.
Unlike common programming languages, use of
== is non-standard (see here).
How to set boolean variable?
In bash, there is not really a boolean type. We can just use literal string
true to set a bool variable and check if variable is equal to string
use_python=true if [[ $use_python = true ]]; then # do something else: # do another thing fi
How to check if a command exists?
We can use
command -v YOUCOMMAND to check if
YOURCOMMAND exists. For example:
if [[ ! "$(command -v rg)" ]]; then # install ripgrep else echo "ripgrep already exists. No action needed." fi
According to here,
which command is not a reliable way to do this,
since it may return an exit code of 0 even if no command is found.
- Introduction to bash if.
- More advanced if usage.
- Difference between
- Check if a command exists in bash script.
- How to declare boolean variable.
you will see
unbound variableerror message. ↩︎
License CC BY-NC-ND 4.0