10

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?

5
  • what are you trying to do? your if statement is missing a fi. Commented Mar 21, 2015 at 14:48
  • Sorry. Forgot to add it here. Commented Mar 21, 2015 at 14:49
  • That's not the correct syntax for an if. This will work: x = $(if [ 2 = 2 ]; then echo equal; else echo "not equal; fi). See gnu.org/software/bash/manual/bash.html#Conditional-Constructs . Note that case matters -- If and if are not the same. Commented Mar 21, 2015 at 14:50
  • if you want to echo it in one line. you need echo -n text. Commented Mar 21, 2015 at 14:50
  • Please take a look: shellcheck.net Commented Mar 21, 2015 at 15:08

2 Answers 2

15

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.

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

2 Comments

How about if I have a variable called $number which a 5, how would put that into the if statement?
How about reading the bash basics ? tldp.org/LDP/Bash-Beginners-Guide/html
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.

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.