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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With