Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return exit code 0 from a failed command

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
like image 776
meso_2600 Avatar asked Mar 21 '16 11:03

meso_2600


People also ask

How do you exit a script if command fails?

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 do I return an 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.

What is a 0 exit code?

# 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).

What is exit code 0 bash?

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.


1 Answers

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.

like image 163
Michael Daffin Avatar answered Sep 20 '22 21:09

Michael Daffin