unix 如何从失败的命令返回退出代码0

lhcgjxsq  于 2022-11-04  发布在  Unix
关注(0)|答案(2)|浏览(231)

我想从一个失败的命令返回退出代码“0”。有没有更简单的方法可以做到这一点,而不是:

function a() {
  ls aaaaa 2>&1;
}

if ! $(a); then
  return 0
else
  return 5
fi
njthzxwz

njthzxwz1#

只需将return 0附加到函数中,就可以强制函数始终成功退出。

function a() {
  ls aaaaa 2>&1
  return 0
}

a
echo $? # prints 0

如果出于任何原因希望内联执行此操作,可以将|| true附加到命令:

ls aaaaa 2>&1 || true
echo $? # prints 0

如果您希望反转退出状态,只需在命令前面加上!即可

! ls aaaaa 2>&1
echo $? # prints 0

! ls /etc/resolv.conf 2>&1
echo $? # prints 1

此外,如果您陈述了您试图实现的总体目标,我们可能会指导您找到更好的答案。

lfapxunr

lfapxunr2#

对于某些人来说,尝试timeout命令可能会有帮助,因为这些命令希望停止输入(如SIGINT =键盘中断),如下所示:
timeout 10 kubectl proxy &
这将执行kubectl代理10秒(以便您可以使用代理执行所需的操作),然后将正常终止kubectl proxy
例如:

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

echo $?
0

超时的帮助也将有助于特定的情况

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

相关问题