summaryrefslogtreecommitdiffhomepage
path: root/bash.html.markdown
diff options
context:
space:
mode:
authorLevi Bostian <levi.bostian@gmail.com>2015-10-15 13:02:14 -0500
committerLevi Bostian <levi.bostian@gmail.com>2015-10-15 13:02:14 -0500
commit560b93d109595d49f7ceb2e5615e33a822dbbdee (patch)
tree75834ca653cf5aa6d8f2b89b418f278639878ed8 /bash.html.markdown
parent063c96225483b50aa5ff6c54a486b59f037d1366 (diff)
parentf4022052471d6dc0a9c2fb8794e1352253b4c5ad (diff)
Merge pull request #1513 from awalGarg/patch-3
[bash/en] use $var with quotes in conditions
Diffstat (limited to 'bash.html.markdown')
-rw-r--r--bash.html.markdown13
1 files changed, 11 insertions, 2 deletions
diff --git a/bash.html.markdown b/bash.html.markdown
index 191f916a..211d2944 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -90,17 +90,26 @@ else
echo "Your name is your username"
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
echo "Always executed" || echo "Only executed if first command fails"
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:
-if [ $Name == "Steve" ] && [ $Age -eq 15 ]
+if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
then
echo "This will run if $Name is Steve AND $Age is 15."
fi
-if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
+if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
echo "This will run if $Name is Daniya OR Zach."
fi