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;
}
if ! $(a); then
return 0
else
return 5
fi
Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
How to get the exit code of a command. To get the exit code of a command type echo $? at the command prompt. In the following example a file is printed to the terminal using the cat command.
# By convention, an 'exit 0' indicates success, #+ while a non-zero exit value means an error or anomalous condition. # See the "Exit Codes With Special Meanings" appendix. $? is especially useful for testing the result of a command in a script (see Example 16-35 and Example 16-20).
For the bash shell's purposes, a command which exits with a zero (0) exit status has succeeded. A non-zero (1-255) exit status indicates failure. If a command is not found, the child process created to execute it returns a status of 127.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With