0

I test the following bash file test.sh. But how to explain the output. Sometimes I would remember quoting string variables means preserving whitespace in a single variable, but how to understand it instead of remembering it.

list="one two three"
for a in $list
do
    echo "$a"
done 

for a in "$list"
do
    echo "$a"
done

output:
one
two
three
one two three

Hel
  • 305
  • 5
  • 14
  • 2
    Double-quoting prevents **word-splitting**. The default **Internal Field Separator (IFS)** is `$' \t\n'` (`space`, `tab`, `newline`) controls how unquoted strings are split by the shell. (which is called **word-splitting**). Meaning an unquoted string is split by the shell on any occurrence of a character in `IFS`. Double-quoting prevents ***word-splitting***. – David C. Rankin Aug 23 '16 at 01:12

1 Answers1

1

Continuing from the comment and explanation of word-splitting and the Internal Field Separator, here is a short example that should help:

#!/bin/bash

list="one two three"

printf "\nDefault IFS (space, tab, newline):\n\n"
for a in $list
do
    echo "$a"
done

for a in "$list"
do
    echo "$a"
done

printf "\nIFS breaking only on newline:\n\n"
IFS=$'\n'
for a in $list
do
    echo "$a"
done

for a in "$list"
do
    echo "$a"
done

(if you continue in a script and don't exit after setting IFS to a new value and need to restore the current (or default) IFS, either save the current (e.g. curifs="$IFS" and restore when done with your block, IFS="$curifs") or just reset to the default (e.g. IFS=$' \t\n'). you can also, just run your block with the new IFS in a subshell, e.g. (IFS=$',\n'; #do stuff), or in a while block, e.g. while IFS=$'\n' read -r line; do ... )

Example Use/Output

$ bash ifs.sh
Default IFS (space, tab, newline):

one
two
three
one two three

IFS breaking only on newline:

one two three
one two three
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85