Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

linux - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...