0

(Using Bash 4.4 and 5.0)

I am dealing with the issue of filenames that contain spaces, newlines and backslashes. I often read the suggestion to use code like this:

oldIFS=$IFS 
IFS= 

while read -rd '' LINE ; do
     ...

or

while IFS= read -rd '' LINE ; do
   ...

However, I find the use of the IFS variable in this context isn't necessary. Apparently so:

I have a directory with these files:

$ ls -a1
.
..
he\llo
hello?w o r l d
listing

The ? in the fourth one stands for a newline. The file listing is the script that produces the output further down below:

$ cat listing
#!/bin/bash

#IFS=
i=0

while read -rd '' FILE; do
    (( i++ ))
    echo -n $i"  "
    ls -ld "$FILE"
done

Now using find -print0 | ./listing gives me this output"

$ find -print0 | ./listing
1  drwxr-xr-x 2 pi pi 4096 Feb 15 16:34 .
2  -rw-r--r-- 1 pi pi 6 Feb 15 06:12 ./hello?w o r l d
3  -rw-r--r-- 1 pi pi 6 Feb 15 05:30 ./he\llo
4  -rwxr--r-- 1 pi pi 99 Feb 15 16:34 ./listing

Which is totally okay. The result is the same if I remove the # in front of IFS in the script listing.

So, modifying IFS doesn't appear to be necessary here.

Am I missing an angle? Under what circumstances would the IFS= be required here?

  • I don't think setting IFS= (to null?) is the same as unset IFS. – Marcel Feb 15 at 8:56
  • I also checked what happens when I unset IFS - by replacing the line 'IFS=' with 'unset IFS'. No difference. Apparently IFS is not involved in the operation or its content doesn't matter. – Arjen Feb 15 at 9:31
  • 2
    read will strip flanking $IFS whitespace off from the read word (with the default value of $IFS). Related: Understanding "IFS= read -r line" – Kusalananda Feb 15 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.