I want to write code like this:
command="some command"
safeRunCommand $command
safeRunCommand() {
cmnd=$1
$($cmnd)
if [ $? != 0 ]; then
printf "Error when executing command: '$command'"
exit $ERROR_CODE
fi
}
But this code does not work the way I want. Where did I make the mistake?
Below is the fixed code:
Now if you look into this code, the few things that I changed are:
typesetis not necessary, but it is a good practice. It makescmndandret_codelocal tosafeRunCommandret_codeis not necessary, but it is a good practice to store the return code in some variable (and store it ASAP), so that you can use it later like I did inprintf "Error: [%d] when executing command: '$command'" $ret_codesafeRunCommand "$command". If you don’t thencmndwill get only the valuelsand notls -l. And it is even more important if your command contains pipes.typeset cmnd="$*"instead oftypeset cmnd="$1"if you want to keep the spaces. You can try with both depending upon how complex is your command argument.Note: Do remember some commands give 1 as the return code even though there isn’t any error like
grep. Ifgrepfound something it will return 0, else 1.I had tested with KornShell and Bash. And it worked fine. Let me know if you face issues running this.