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?
Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.
ksh. exit will cause the calling shell or shell script to exit with the exit status specified by n . The value will be the least significant 8 bits of the specified status. If n is omitted then the exit status is that of the last command executed.
You can simply do a echo $? after executing the command/bash which will output the exit code of the program. Every command returns an exit status (sometimes referred to as a return status or exit code).
Exit Codes. Exit codes are a number between 0 and 255, which is returned by any Unix command when it returns control to its parent process. Other numbers can be used, but these are treated modulo 256, so exit -10 is equivalent to exit 246 , and exit 257 is equivalent to exit 1 .
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, the few things that I changed are:
typeset
is not necessary, but it is a good practice. It makes cmnd
and ret_code
local to safeRunCommand
ret_code
is 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 in printf "Error: [%d] when executing command: '$command'" $ret_code
safeRunCommand "$command"
. If you don’t 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 the return code even though there isn't any error like grep
. If grep
found 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.
Try
safeRunCommand() { "$@" if [ $? != 0 ]; then printf "Error when executing command: '$1'" exit $ERROR_CODE fi }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With