7

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?

vidit
  • 6,293
  • 3
  • 32
  • 50
space149
  • 83
  • 1
  • 1
  • 6

2 Answers2

13

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.

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
baky
  • 631
  • 1
  • 8
  • 17
  • How about if I have a variable called $number which a 5, how would put that into the if statement? – space149 Mar 21 '15 at 17:26
  • How about reading the bash basics ? http://www.tldp.org/LDP/Bash-Beginners-Guide/html/ – baky Apr 09 '15 at 09:09
12

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.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151