Bash: if [ "echo test" == "test"]; 然后回显“echo test output test on shell” fi; 可能的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8463145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash: if [ "echo test" == "test"]; then echo "echo test outputs test on shell" fi; Possible?
提问by cedivad
Is it possible with bash to execute a command from shell and if it returns a certain value (or an empty one) execute a command?
bash 是否可以从 shell 执行命令,如果它返回某个值(或空值),则执行命令?
if [ "echo test" == "test"]; then
echo "echo test outputs test on shell"
fi
回答by Mat
Yes, you can use backticks or $()
syntax:
是的,您可以使用反引号或$()
语法:
if [ $(echo test) = "test" ] ; then
echo "Got it"
fi
You should replace $(echo test)
with
你应该$(echo test)
用
"`echo test`"
or
或者
"$(echo test)"
if the output of the command you run can be empty.
如果您运行的命令的输出可以为空。
And the POSIX "stings are equal" test
operator is =
.
POSIX“stings are equal”test
运算符是=
.
回答by bjarneh
something like this?
像这样的东西?
#!/bin/bash
EXPECTED="hello world"
OUTPUT=$(echo "hello world!!!!")
OK="$?" # return value of prev command (echo 'hellow world!!!!')
if [ "$OK" -eq 0 ];then
if [ "$OUTPUT" = "$EXPECTED" ];then
echo "success!"
else
echo "output was: $OUTPUT, not $EXPECTED"
fi
else
echo "return value $OK (not ok)"
fi
回答by Zsolt Botykai
You can check the exit_code
of the previous program like:
您可以检查exit_code
以前的程序,如:
someprogram
id [[ $? -eq 0 ]] ; then
someotherprogram
fi
Note, normally the 0
exit code means successful finish.
注意,通常0
退出代码意味着成功完成。
You can do it shorter:
你可以做得更短:
someprogram && someotherprogram
With the above someotherprogram
only executes if someprogram
finished successfully. Or if you want to test for unsuccessful exit:
以上someotherprogram
仅someprogram
在成功完成后才执行。或者,如果您想测试不成功的退出:
someprogram || someotherprogram
HTH
HTH
回答by Zsolt Botykai
Putting the command betweeen $( and ) or backticks (`) will substitute that expression into the return value of the command. So basically:
将命令放在 $( 和 ) 或反引号 (`) 之间会将该表达式替换为命令的返回值。所以基本上:
if [ `echo test` == "test"]; then
echo "echo test outputs test on shell"
fi
or
或者
if [ $(echo test) == "test"]; then
echo "echo test outputs test on shell"
fi
will do the trick.
会做的伎俩。