Bash:if ["echo test"=="test"]; 然后回声"回声测试输出测试shell"fi; 可能?

ced*_*vad 4 bash

是否可以使用bash从shell执行命令,如果它返回某个值(或空值)执行命令?

if [ "echo test" == "test"]; then
  echo "echo test outputs test on shell"
fi
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 6

是的,您可以使用反引号或$()语法:

if [ $(echo test) = "test" ] ; then
  echo "Got it"
fi
Run Code Online (Sandbox Code Playgroud)

此时应更换$(echo test)

"`echo test`"
Run Code Online (Sandbox Code Playgroud)

要么

"$(echo test)"
Run Code Online (Sandbox Code Playgroud)

如果您运行的命令的输出可以为空.

并且POSIX"stings是相同的" test运算符是=.


小智 5

像这样的东西?

#!/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
Run Code Online (Sandbox Code Playgroud)