How to return exit code 0 from a failed command

前端 未结 1 1172
礼貌的吻别
礼貌的吻别 2021-01-18 01:24

I would like to return exit code \"0\" from a failed command. Is there any easier way of doing this, rather than:

function a() {
  ls aaaaa 2>&1;
}

i         


        
相关标签:
1条回答
  • 2021-01-18 01:53

    Simply append return 0 to the function to force a function to always exit successful.

    function a() {
      ls aaaaa 2>&1
      return 0
    }
    
    a
    echo $? # prints 0
    

    If you wish to do it inline for any reason you can append || true to the command:

    ls aaaaa 2>&1 || true
    echo $? # prints 0
    

    If you wish to invert the exit status simple prepend the command with !

    ! ls aaaaa 2>&1
    echo $? # prints 0
    
    ! ls /etc/resolv.conf 2>&1
    echo $? # prints 1
    

    Also if you state what you are trying to achieve overall we might be able to guide you to better answers.

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