Issue
I'm new to Bash scripting and was wondering which is the recommended way to handle if-else statements in this case since all of them seem to work.
#!/bin/bash
bla=false
if [ "$bla" = false ]; then
echo "Method 1"
fi
if `! $bla` ; then
echo "Method 2"
fi
if [ -n $bla ] ; then
echo "Method 3"
fi
Solution
if `! $bla`;
is particularly bad because it attempts to run the empty string as a command.
But really, none of these are particularly good.
Using "false" and "true" probably doesn't do what you imagine. The shell primarily distinguishes between empty and non-empty strings so perhaps use that instead.
bla=""
if ! [ "$bla" ]; then
echo "Method 1, fixed"
fi
There is no concept of boolean variables, but the command true
returns zero and false
returns nonzero, which again is meaningful to the shell.
bla=false
if ! $bla; then
echo "Method 2 fixed; but really, don't put commands in variables"
fi
... but really, don't put commands in variables. (See also https://mywiki.wooledge.org/BashFAQ/050)
Just to reiterate,
bla=false
if ! `$bla`; then
echo "Really, don't do this!"
fi
will run bla
, then take the output of that (which is the empty string; false
and true
don't print anything) and attempt to run that as a command, and examine its exit code. You probably were thinking simply
if $bla; then
but again, don't put commands in variables.
One more time,
bla='echo "crickets"'
if ! `$bla` ...
will end up running crickets
as the command whose result code if
will examine.
Apart from the tortured pretzel logic, you don't have to have a lot of fantasy to come up with scenarios where this is too obscure, convoluted, unmaintainable, and/or insecure to be useful.
Bottom line, beginners often imagine that [
or backticks are somehow required syntax where they are not. Once you understand how commands return exit codes and that variables are always strings, the jigsaw pieces will start to fall into place. The shell is actually quite logical, but very different from many other programming languages.
Answered By - tripleee Answer Checked By - David Marino (WPSolving Volunteer)