Bash – variables in double quotes vs without quotes

Bash variables without double quotes can give surprising results. The special characters inside a variable when not double quoted, gets interpreted by bash. Few points to note:

  1. echo will pint newline as space if variable is not quotes.
  2. bash for loop will treat a string with spaces/newlines as multiple values delimited by space.

Here are some code examples

ls outcome – echo variable with quote vs without quote

#!/bin/bash
mkdir -p testdir
cd testdir; touch file1.txt; touch file2.txt
a=$(ls)
echo '===echo $a [newlines not expected]==='
echo $a
echo '===echo "$a" [newlines expected]==='
echo "$a"
===echo $a [newlines not expected]===
file1.txt file2.txt
===echo "$a" [newlines expected]===
file1.txt
file2.txt
Env: GNU bash, version 4.3.11

ls outcome – for loop iteration on variable with quote vs without quote

#!/bin/bash
mkdir -p testdir
cd testdir; touch file1.txt; touch file2.txt
a=$(ls)
echo '===iterating over $a==='
for i in $a
do
  echo "val: $i"
done
echo '===iterating over "$a"==='
for i in "val: $a"
do
  echo "$i"
done
===iterating over $a===
val: file1.txt
val: file2.txt
===iterating over "$a"===
val: file1.txt
file2.txt
Env: GNU bash, version 4.3.11
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments