如何检查命令是否成功?
有没有办法检查执行命令是否有错误?
示例:
test1=`sed -i "/:@/c connection.url=jdbc:oracle:thin:@$ip:1521:$dataBase" $search` valid $test1 function valid () { if $test -eq 1; then echo "OK" else echo "ERROR" fi }
我已经尝试过这样做,但它似乎无法正常工作。 我不知道怎么做。
返回值存储在$?
。 0表示成功,其他表示错误。
some_command if [ $? -eq 0 ]; then echo OK else echo FAIL fi
与任何其他文本值一样,您可以将其存储在变量中以供将来比较:
some_command retval=$? do_something $retval if [ $retval -ne 0 ]; then echo "Return code was not zero but $retval" fi
有关可能的比较运算符,请参阅man test
。
如果您只需要知道命令是成功还是失败,请不要打扰测试$?
,直接测试命令。 例如:
if some_command; then printf 'some_command succeeded\n' else printf 'some_command failed\n' fi
并且将输出分配给变量不会改变返回值(当然,除非当stdout不是终端时表现不同)。
if output=$(some_command); then printf 'some_command succeded, the output was «%s»\n' "$output" fi
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals更详细地解释了。
command && echo OK || echo Failed
$? 应包含上一个命令的退出状态,该命令应该为零,表示没有错误。
所以,像;
cd /nonexistant if [ $? -ne 0 ] then echo failed else echo success! fi
对于大多数情况,使用&&构造来链接需要相互依赖的命令更容易。 所以cd /nonexistant && echo success!
不会回应成功,因为命令在&&之前中断。 这个的推论是||,其中cd /nonexistant || echo fail
cd /nonexistant || echo fail
会因为cd失败而失败。 (如果您使用类似|| exit的内容,这将变得非常有用,如果上一个命令失败,它将结束脚本。)
command && echo $? || echo $?
为了防止您的命令出错 :
execute [INVOKING-FUNCTION] [COMMAND]
execute () { error=$($2 2>&1 >/dev/null) if [ $? -ne 0 ]; then echo "$1: $error" exit 1 fi }
灵感来自精益制造:
- 设计错误是不可能的
- 使步骤最小
- 逐个完成项目
- 让任何人都明白
应该注意的是, if...then...fi
和&&
/ ||
方法类型处理我们想要测试的命令返回的退出状态(成功时为0); 但是,如果命令失败或无法处理输入,某些命令不会返回非零退出状态。 这意味着通常的if
和&&
/ ||
方法不适用于那些特定的命令。
例如,在Linux上GNU file
如果收到一个不存在的文件作为参数仍然以0退出,并且find
无法找到指定的文件用户。
$ find . -name "not_existing_file" $ echo $? 0 $ file ./not_existing_file ./not_existing_file: cannot open `./not_existing_file' (No such file or directory) $ echo $? 0
在这种情况下,我们可以处理这种情况的一种可能方法是读取stderr
/ stdin
消息,例如通过file
命令返回的消息,或者像find
那样解析命令的输出。 为此目的,可以使用case
陈述。
$ file ./doesntexist | while IFS= read -r output; do > case "$output" in > *"No such file or directory"*) printf "%s\n" "This will show up if failed";; > *) printf "%s\n" "This will show up if succeeded" ;; > esac > done This will show up if failed $ find . -name "doesn'texist" | if ! read IFS= out; then echo "File not found"; fi File not found
(这是我在unix.stackexchange.com上关于相关问题的答案的转贴 )
正如许多其他答案中所提到的,对$?
的简单测试$?
会这样做的
if [ $? -eq 0 ]; then something; fi
如果要测试命令是否失败 ,可以在bash
使用较短版本(但可能是矫枉过正),如下所示:
if (($?)); then something; fi
这通过使用(( ))
算术模式工作,所以如果命令返回success
,即$? = 0
$? = 0
然后测试评估为((0))
哪些测试为false
,否则它将返回true
。
要测试是否成功 ,您可以使用:
if ! (($?)); then something; fi
但它已经没有第一个例子短。