0

I have this example and i want to get on screen both condition and good Code:

if [ `echo condition` ]; then echo good; fi

The output that i want to get:

condition
good

The output that i got:

good

As the command echo condition will be replaced with another command. The if statement must check the return code of the condition command.

3 Answers3

2

Simply store it in a variable:

cond=$(echo condition)
if [ "$cond" ] ; then
    echo "$cond"
    echo good
fi
MichalH
  • 1,062
  • 9
  • 20
0

Do not use backticks anymore nowadays.

Store the output of your sub shell in a variable:

if condition=$(echo condition); then
  echo "$condition"
  echo good
fi

If you want to return the exit value of the sub shell, you have to write a function:

get-condition-result()
{
  local condition
  local result
  if condition=$(echo condition); then
    result=$?
    echo "$condition"
    echo good
  else
    result=$?
  fi
  return "$result"
}
ceving
  • 21,900
  • 13
  • 104
  • 178
0

Solution found here: https://stackoverflow.com/a/13343457/12953642

You can run your command without any additional syntax. For example, the following checks the exit code of grep to determine whether the regular expression matches or not:

if echo condition
then
    echo "good"
fi
if echo "condition" && curl
then
    echo "good"
else
    echo "error in command"
fi

Output:

condition
good
condition
curl: try 'curl --help' or 'curl --manual' for more information
error in command