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 working the way I want. Where I made mistake?
Below is the fixed code:
#!/bin/ksh
safeRunCommand() {
typeset cmnd="$*"
typeset ret_code
echo cmnd=$cmnd
eval $cmnd
ret_code=$?
if [ $ret_code != 0 ]; then
printf "Error : [%d] when executing command: '$cmnd'" $ret_code
exit $ret_code
fi
}
command="ls -l | grep p"
safeRunCommand "$command"
Now if you look into this code few things that I changed are:
typeset
is not necessary but a good practice. It make cmnd
and ret_code
local to safeRunCommand
ret_code
is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
safeRunCommand "$command"
. If you dont then cmnd
will get only the value ls
and not ls -l
. And it is even more important if your command contains pipes.typeset cmnd="$*"
instead of typeset 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 return code even though there is no error like grep
. If grep
found something it will return 0 else 1.
I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.