0

Is it possible to set a variable from the output of a command inside of a conditional where the conditional is false if nothing gets assigned to the variable.

If I set the variable to a grep with no return and then test:

test=$(echo hello | grep 'helo')
if [[ ! -z $test ]]; then
  echo "is set"
else
  echo "not set"
fi

Output: not set (this is expected)

But I'm trying to put it all into one statement like this:

test=
if [[ ! -z test=$(echo hello | grep 'helo') ]]; then
  echo "is set"
else
  echo "not set"
fi

output: "is set" (expected not set)

3
  • 1
    test= is the same as test="", so the variable is not unset, but set to the empty string. Commented Feb 22, 2018 at 20:22
  • 1
    @Socowi, ...the variable isn't being set at all; the string test= is being compared against the empty string, not evaluated as an assignment. Commented Feb 22, 2018 at 20:52
  • 1
    @ArchieArchbold : In your second example, the variable test doesn't get assigned inside the if statement. Instead, -z looks at the string test=SOMETHING, and this string is always non-empty, because no matter what SOMETHING evaluates to, the argument of the -z operator always starts with test=. Side note: If you replace ! -z by -n, the code gets a bit more readable. Commented Feb 23, 2018 at 7:20

2 Answers 2

4

grep returns success if there is a match, so you can just do:

if test=$(echo hello | grep 'helo')
then
  echo "Match: $test"
else
  echo "No match"
fi

If you're running something that doesn't differentiate by exit code, you can assign and check in two statements on the same line:

if var=$(cat) && [[ -n $var ]] 
then
  echo "You successfully piped in some data."
else
  echo "Error or eof without data on stdin."
fi

(or ; instead of && if you want to inspect the result even when the command reports failure)

Sign up to request clarification or add additional context in comments.

1 Comment

exactly what I was looking for. Thank you much!
0

Bit of a hack, using the shell's parameter expansion alternate value syntax, echo -e and some backspaces:

test=$(echo hello | grep 'helo'); echo -e not${test:+\\b\\b\\bis} set

Which outputs is set or not set depending on what grep finds.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.