15
votes

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
1
How about return ! auser000001
No need for command substitution simple use if ! a; then ...andlrc
if the stderr output is written to stdout, in-case of command failures the script will throw a nasty error which can be avoided by silencing the command output and by getting only the command execution status from $?Inian
If I understand you right, you want to exit status "OK", if the ls command fails, and exit status 5 (BTW, why are you writing return and not exit?), if the ls command succeeds. Why, then, do you need to do an ls? Wouldn't it be simpler (and clearer to understand) to query the existence of aaaaa, i.e. something like [[ -e aaaaa ]] && echo 'ERROR: aaaaa exists!' && exit 5 ?user1934428
@dev-null have to use cmd subst due to -e and couple other switchesmeso_2600

1 Answers

28
votes

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.