Friday, May 3, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 727  / 3 Years ago, sun, september 5, 2021, 10:34:51

Are the following two boolean expressions the same?



if [ -n $1 ] ; then

if [ -n "$1" ] ; then


If not - When should you put a variable in quotes?


More From » bash

 Answers
1

Here is an example that should demonstrate the difference



~$ t="alfa beta"
~$ if [ -n $t ] ; then echo OK ; fi
bash: [: alfa: binary operator expected
~$ if [ -n "$t" ] ; then echo OK ; fi
OK
~$ ls blah*
blah1 blah2 blah3
~$ t="blah*"
~$ if [ -n "$t" ] ; then echo OK ; fi
OK
~$ if [ -n $t ] ; then echo OK ; fi
bash: [: too many arguments


In other words, with quotes, the $t is expanded only once and put in quotes as a single argument to test ([ is just an alias to test). Without quotes, it is substituted by the contents of $t and then expanded again.


[#35845] Monday, September 6, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calcur

Total Points: 189
Total Questions: 80
Total Answers: 95

Location: Burkina Faso
Member since Thu, Dec 15, 2022
1 Year ago
;