Bharath Kumar Reddy
Bharath Kumar Reddy

Reputation: 11

shell - wrapping variables in quotes

Can someone please explain me what is the use of wrapping variables in quotes in shell scripting. I know that it will be helpful to bind two or more strings but what is the purpose if I have a single string/integer.

X=0
while [ -n "$X" ]
do
   echo "Enter some text (RETURN to quit)"
   read X
   if [ -n "$X" ]; then
      echo "You said: $X"
   fi
done

If I don't keep $X in quotes in line 2, the script is not terminating even after I press RETURN.

Upvotes: 1

Views: 53

Answers (1)

Onkar Kamatkar
Onkar Kamatkar

Reputation: 212

Run the script in debug mode to see the difference regarding how the condition is interpreted.

bash -x ${shell_file}
  1. When quotes are mentioned - + '[' -n '' ']'
  2. When quotes are not mentioned - + '[' -n ']' (which is always true)

X will be empty when RETURN key is pressed, but interpreter will consider only when it is quoted.

Upvotes: 1

Related Questions