How to avoid a bash script from failing when -e option is set?

前端 未结 3 630
误落风尘
误落风尘 2021-01-03 19:24

I have a bash script with -e option set, which fails the whole script on the very first error.

In the script, I am trying to do an ls on a

相关标签:
3条回答
  • 2021-01-03 19:31

    Another option is to use trap to catch the EXIT signal:

    trap 'echo "ls failed" ; some_rescue_action' EXIT
    ls /non_exist
    
    0 讨论(0)
  • 2021-01-03 19:33

    You can "catch" the error using || and a command guaranteed to exit with 0 status:

    ls $PATH || echo "$PATH does not exist"
    

    Since the compound command succeeds whether or not $PATH exists, set -e is not triggered and your script will not exit.

    To suppress the error silently, you can use the true command:

    ls $PATH || true
    

    To execute multiple commands, you can use one of the compound commands:

    ls $PATH || { command1; command2; }
    

    or

    ls $PATH || ( command1; command2 )
    

    Just be sure nothing fails inside either compound command, either. One benefit of the second example is that you can turn off immediate-exit mode inside the subshell without affecting its status in the current shell:

    ls $PATH || ( set +e; do-something-that-might-fail )
    
    0 讨论(0)
  • 2021-01-03 19:41

    one solution would be testing the existence of the folder

    function myLs() {
        LIST=""
        folder=$1
        [ "x$folder" = "x" ] && folder="."
        [ -d $folder ] && LIST=`ls $folder`
        echo $LIST
    }
    

    This way bash won't fail if $folder does not exist

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