How to return exit code 0 from a failed command

Viewed 24811

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
2 Answers

It may be helpful for some people to try timeout command for commands that expect input (like SIGINT = keyboard interrupt) to be stopped like:

timeout 10 kubectl proxy &

This will execute kubectl proxy for 10 seconds (so you can perform the actions you need using the proxy) and then will gracefully terminate kubectl proxy

example:

timeout 3 kubectl proxy &
[1] 759
Starting to serve on 127.0.0.1:8001

echo $?
0

The help of timeout will also help on specific cases

timeout --help
Usage: timeout [OPTION] DURATION COMMAND [ARG]...
  or:  timeout [OPTION]
Start COMMAND, and kill it if still running after DURATION.

Mandatory arguments to long options are mandatory for short options too.
      --preserve-status
                 exit with the same status as COMMAND, even when the
                   command times out
      --foreground
                 when not running timeout directly from a shell prompt,
                   allow COMMAND to read from the TTY and get TTY signals;
                   in this mode, children of COMMAND will not be timed out
  -k, --kill-after=DURATION
                 also send a KILL signal if COMMAND is still running
                   this long after the initial signal was sent
  -s, --signal=SIGNAL
                 specify the signal to be sent on timeout;
                   SIGNAL may be a name like 'HUP' or a number;
                   see 'kill -l' for a list of signals
      --help     display this help and exit
      --version  output version information and exit
Related