space149
space149

Reputation: 93

Unix Bash - Assign if/else to Variable

I have been creating to assign the output of if/else to a variable but keep on getting an error.

For Example:

mathstester=$(If [ 2 = 2 ]
Then echo equal
Else
echo "not equal"

fi)

So whenever I add $mathstester in a script, laid out like this:

echo "Equation: $mathstester"

It should display:

Equation: Equal

Do I need to lay it out differently? Is it even possible?

Upvotes: 8

Views: 38662

Answers (2)

baky
baky

Reputation: 681

The correct way to use if is:

mathtester=$(if [ 2 = 2 ]; then echo "equal"; else echo "not equal"; fi)

For using this in multiline statements you might consider looking link.

Upvotes: 15

Gordon Davisson
Gordon Davisson

Reputation: 125808

Putting the if statement in the assignment is rather clumsy and easy to get wrong. The more standard way to do this is to put the assignment inside the if:

if [ 2 = 2 ]; then
    mathstester="equal"
else
    mathstester="not equal"
fi

As for testing variables, you can use something like if [ "$b" = 2 ] (which'll do a string comparison, so for example if b is "02" it will NOT be equal to "2") or if [ "$b" -eq 2 ], which does numeric comparison (integers only). If you're actually using bash (not just a generic POSIX shell), you can also use if [[ "$b" -eq 2 ]] (similar to [ ], but with somewhat cleaner syntax for more complicated expressions), and (( b == 2 )) (these do numeric expressions only, and have very different syntax). See BashFAQ #31: What is the difference between test, [ and [[ ? for more details.

Upvotes: 12

Related Questions