12/5/2022 Basic shell tests
Memorize how to perform various tests in shell scripting :
The following conditionnal pattern is POSIX
compliant :
if [ condition ]; then
do something
else
do other thing
fi
or with then
on next line :
if [ condition ]
then
do something
else
do other thing
fi
Note that [
is the same as test
(see in Sources, below).
Test if a command does not exists : -x means executable
.
if ! [ -x $(command -v git) ]; then
echo "Warning: git command is not found"
fi
Test if a file (remember, a unix file can be anything) exists : -e means
existing
.
if ! [ -e filename ]; then
echo "Warning: filename is not found"
fi
To be more precise, use -d
or -f
(directory
, regular file
)
Note: In a fish shell script, syntax would be much simpler :
if test -d $HOME/DEV/rust
set -l FOO bar
set -gx FIZ buzz
else
set -gx BAR foo
end
Sources :
man test