[英]How to return exit code 0 from a failed command
我想從失敗的命令中返回退出代碼“0”。 有沒有更簡單的方法可以做到這一點,而不是:
function a() {
ls aaaaa 2>&1;
}
if ! $(a); then
return 0
else
return 5
fi
只需將return 0
附加到函數即可強制函數始終成功退出。
function a() {
ls aaaaa 2>&1
return 0
}
a
echo $? # prints 0
如果您出於任何原因希望內聯,您可以附加|| true
|| 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
此外,如果您說明您想要實現的總體目標,我們可能會指導您獲得更好的答案。
對於希望輸入(如 SIGINT = 鍵盤中斷)停止的命令,嘗試timeout
命令可能會有所幫助,例如:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.