How to ignore return value different then 0 when I have set -e?

前端 未结 2 1472
广开言路
广开言路 2021-01-11 16:15

I often add set -e in my bash scripts. However this time I have to call a command that returns some meaningless number instead of 0 on success. How can I tell b

相关标签:
2条回答
  • 2021-01-11 16:59

    true always returns a zero exit code. So you can do

    command-with-meaningless-return-value || true
    
    0 讨论(0)
  • 2021-01-11 17:00

    If you need to use the value of $? later, you can do:

    # A test funtion to demonstrate different exit status values
    $ exit_with(){ return $1; }
    
    $ exit_with 0
    
    $ echo $?
    0
    
    $ exit_with 4
    
    $ echo $?
    4
    
    $ exit_with 4 || true
    
    $ echo $?
    0
    
    # capture the exit status rather than clobber it
    $ exit_with 4 || exit_status=$?
    
    $ echo $?
    0
    
    $ echo $exit_status
    4
    

    In this case use $exit_status instead of $?. I've not found a way to do something like ?=$? or declare ?=$?

    0 讨论(0)
提交回复
热议问题