[bash/en] use $var with quotes in conditions

This commit is contained in:
Awal Garg 2015-10-14 21:10:28 +05:30
parent 8ec133b295
commit f402205247

View File

@ -90,17 +90,26 @@ else
echo "Your name is your username" echo "Your name is your username"
fi fi
# NOTE: if $Name is empty, bash sees the above condition as:
if [ -ne $USER ]
# which is invalid syntax
# so the "safe" way to use potentially empty variables in bash is:
if [ "$Name" -ne $USER ] ...
# which, when $Name is empty, is seen by bash as:
if [ "" -ne $USER ] ...
# which works as expected
# There is also conditional execution # There is also conditional execution
echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" || echo "Only executed if first command fails"
echo "Always executed" && echo "Only executed if first command does NOT fail" echo "Always executed" && echo "Only executed if first command does NOT fail"
# To use && and || with if statements, you need multiple pairs of square brackets: # To use && and || with if statements, you need multiple pairs of square brackets:
if [ $Name == "Steve" ] && [ $Age -eq 15 ] if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
then then
echo "This will run if $Name is Steve AND $Age is 15." echo "This will run if $Name is Steve AND $Age is 15."
fi fi
if [ $Name == "Daniya" ] || [ $Name == "Zach" ] if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then then
echo "This will run if $Name is Daniya OR Zach." echo "This will run if $Name is Daniya OR Zach."
fi fi