Echoing Weird Variables

Hello guys, i was reading "Quoting variables" from the bash documentation, and i'm stucked on this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#!/bin/bash
# weirdvars.sh: Echoing weird variables.

echo

var="'(]\\{}\$\""
echo $var        # '(]\{}$"
echo "$var"      # '(]\{}$"     Doesn't make a difference.

echo

IFS='\'
echo $var        # '(] {}$"     \ converted to space. Why?
echo "$var"      # '(]\{}$"

# Examples above supplied by Stephane Chazelas.

echo

var2="\\\\\""
echo $var2       #   "
echo "$var2"     # \\"
echo
# But ... var2="\\\\"" is illegal. Why?
var3='\\\\'
echo "$var3"     # \\\\
# Strong quoting works, though.


Source: https://tldp.org/LDP/abs/html/quotingvar.html#FTN.AEN2630

I Don't understand why after the IFS='\', $var without quoting has whitepaces (\ converted to whitespace)

Can someone help me?
Thank you all!!
Last edited on
That's the whole point of IFS. It splits strings into tokens, so you can .e.g iterate over them
1
2
3
4
5
6
7
8
var="a,b,c"
IFS=','
echo "$var"
echo $var

for x in $var; do
  echo $x
done


a,b,c
a b c
a
b
c
Last edited on
I wouldn't recommend learning from the ABS (or shellscripting from TLDP in general). It's full of bugs, errors, and just bad information in general. For this particular example, there's never really a case where you should depend on wordsplitting via IFS hacks to iterate over a scalar string variable. You can make it work, but you can't make it safe and will run into plenty of strange bugs. Bash on the other hand has other native tools and features to make splitting a string into a list safe, and the array datatype (which can store a list) which is the proper way to iterate over a collection.

Some good learning resources:
https://mywiki.wooledge.org/BashGuide
https://mywiki.wooledge.org/WordSplitting
https://mywiki.wooledge.org/Quotes
https://mywiki.wooledge.org/BashFAQ/005
https://mywiki.wooledge.org/BashFAQ/100
Topic archived. No new replies allowed.