When you only have a small number of checks, you can use
[[ $SUUSER != 'root' ]] && { echo "Please run the script as root"; echo exit 1; }
When you have a lot of checks, I would use a die()
function like @erik_dannenberg wrote.
off-topic: You should write your own shell variables in lowercase, like ${su_user}
.
One reason of your proposed function is the possibility of showing which test failed (compare "${su_user}"
with root
). When you want this, make a function like
checkroot()
. You will take a lot of responsibilities when you want to support all normal special characters.
I tried something with support of the [ ... ]
syntax. Do you see what is wrong with this "solution"?
if_exit() { # incorrect function
# skip first '['
shift
# split line around ]
IFS="]" read -r testparams errormessage <<< "${@}"
if [ ${testparams} ] ; then
echo "Test [ ${testparams% } ] failed: ${errormessage# }"
# exit 1
fi
}
if_exit [ -f non_existing_file ] "file not existing"
su_user="root"
if_exit [ "${su_user}" \!= root ] "Please run the script as root"
echo "Another test with wrong user"
su_user="aeris"
if_exit [ "${su_user}" \!= root ] "Please run the script as root"
Looking good, except for the exclamation mark?
It will fail when su_user
is empty or has spaces (su_user="I dont want to be tested"
).
You can make a work-around for this problem in the if_exit()
function, but will continue to meet new problems (like spaces in the filename).
You can look for the source code of test.c, but you should drop your nice intentions and choose for another solution (die()
or compare_strings()
).