Get exit code for command in bash/ksh

前端 未结 5 1038
死守一世寂寞
死守一世寂寞 2021-02-01 01:08

I want to write code like this:

command=\"some command\"

safeRunCommand $command

safeRunCommand() {
   cmnd=$1

   $($cmnd)

   if [ $? != 0 ]         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 01:42

    There are several things wrong with your script.

    Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

    It's good practice to surround your variable references with curly braces, too. Your code might look like:

    #!/bin/sh
    command="/bin/date -u"          #...Example Only
    
    safeRunCommand() {
       cmnd="$@"                    #...insure whitespace passed and preserved
       $cmnd
       ERROR_CODE=$?                #...so we have it for the command we want
       if [ ${ERROR_CODE} != 0 ]; then
          printf "Error when executing command: '${command}'\n"
          exit ${ERROR_CODE}        #...consider 'return()' here
       fi
    }
    
    safeRunCommand $command
    command="cp"
    safeRunCommand $command
    

提交回复
热议问题