使用bash是否可以从shell执行命令,如果它返回某个值(或空值),是否可以执行命令?
if [ "echo test" == "test"]; then
echo "echo test outputs test on shell"
fi发布于 2011-12-11 18:02:08
可以,您可以使用反引号或$()语法:
if [ $(echo test) = "test" ] ; then
echo "Got it"
fi您应该将$(echo test)替换为
"`echo test`"或
"$(echo test)"如果您运行的命令的输出可以为空。
并且POSIX“字符串相等”的test运算符是=。
发布于 2011-12-11 18:13:16
像这样的东西?
#!/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发布于 2011-12-11 18:02:40
您可以查看前一个程序的exit_code,如下所示:
someprogram
id [[ $? -eq 0 ]] ; then
someotherprogram
fi注意,通常0退出代码表示成功完成。
你可以做得更短一些:
someprogram && someotherprogram仅当someprogram成功完成时,才会执行上面的someotherprogram。或者,如果您想测试不成功的退出:
someprogram || someotherprogramHTH
https://stackoverflow.com/questions/8463145
复制相似问题