Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix Bash - Assign if/else to Variable

Tags:

bash

unix

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?

like image 763
space149 Avatar asked Mar 21 '15 14:03

space149


People also ask

How do you assign a value to a variable in a shell script using IF statement?

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. if you want to echo it in one line.

What is bash if [- N?

A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.


2 Answers

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.

like image 180
Gordon Davisson Avatar answered Oct 28 '22 21:10

Gordon Davisson


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.

like image 10
baky Avatar answered Oct 28 '22 22:10

baky