If the following example, which sets the IFS
environment variable to a line feed character...
IFS=$'\n'
I know what the IFS
environment variable is, and what the \n
character is (line feed), but why not just use the following form:
IFS="\n"
(which does not work)?
For example, if I want to loop through every line of a file and want to use a for loop, I could do this:
for line in (< /path/to/file); do
echo "Line: $line"
done
However, this won't work right unless IFS
is set to a line feed character. To get it to work, I'd have to do this:
OLDIFS=$IFS
IFS=$'\n'
for line in (< /path/to/file); do
echo "Line: $line"
done
IFS=$OLDIFS
Note: I don't need another way for doing the same thing, I know many other already... I'm only curious about that $'\n'
and wondered if anyone could give me an explanation on it.
Normally bash
doesn't interpret escape sequences in string literals. So if you write \n
or "\n"
or '\n'
, that's not a linebreak - it's the letter n
(in the first case) or a backslash followed by the letter n
(in the other two cases).
$'somestring'
is a syntax for string literals with escape sequences. So unlike '\n'
, $'\n'
actually is a linebreak.