Get exit code for command in bash/ksh

前端 未结 5 1001
死守一世寂寞
死守一世寂寞 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:32

    The normal idea would be to run the command and then use $? to get the exit code. However, some times you have multiple cases in which you need to get the exit code. For example, you might need to hide it's output but still return the exit code, or print both the exit code and the output.

    ec() { [[ "$1" == "-h" ]] && { shift && eval $* > /dev/null 2>&1; ec=$?; echo $ec; } || eval $*; ec=$?; }
    

    This will give you the option to suppress the output of the command you want the exit code for. When the output is suppressed for the command, the exit code will directly be returned by the function.

    I personally like to put this function in my .bashrc file

    Below I demonstrate a few ways in which you can use this:


    # In this example, the output for the command will be
    # normally displayed, and the exit code will be stored
    # in the variable $ec.
    
    $ ec echo test
    test
    $ echo $ec
    0
    

    # In this example, the exit code is output
    # and the output of the command passed
    # to the `ec` function is suppressed.
    
    $ echo "Exit Code: $(ec -h echo test)"
    Exit Code: 0
    

    # In this example, the output of the command
    # passed to the `ec` function is suppressed
    # and the exit code is stored in `$ec`
    
    $ ec -h echo test
    $ echo $ec
    0
    

    Solution to your code using this function

    #!/bin/bash
    if [[ "$(ec -h 'ls -l | grep p')" != "0" ]]; then
        echo "Error when executing command: 'grep p' [$ec]"
        exit $ec;
    fi
    

    You should also note that the exit code you will be seeing will be for the grep command that's being run, as it is the last command being executed. Not the ls.

提交回复
热议问题