Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: if [ "echo test" == "test"]; then echo "echo test outputs test on shell" fi; Possible?

Tags:

bash

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?

if [ "echo test" == "test"]; then
  echo "echo test outputs test on shell"
fi
like image 477
cedivad Avatar asked Dec 11 '11 09:12

cedivad


2 Answers

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
like image 23
bjarneh Avatar answered Sep 28 '22 07:09

bjarneh


Yes, you can use backticks or $() syntax:

if [ $(echo test) = "test" ] ; then
  echo "Got it"
fi

You should replace $(echo test) with

"`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 =.

like image 105
Mat Avatar answered Sep 28 '22 06:09

Mat