Imagine a file list, list.txt, like this one

image1.jpg
image2.jpg
image3.jpg

Naturally you could deal with it like so

cat list.txt | while read i; do
   FILE="$i"
   dosomething "$FILE"
done

Or just use the $i variable as its already the file and do a one liner like this:

cat list.txt | while read i; do dosomething “$i”; done This will dosomething against image1.jpg, image2.jpg and image3.jpg.

Easy simple loop.
Now imagine a file list with special characters like this one, listB.txt:

file1.txt
file2.txt
file3 "dot text".txt
file4 "'dot text.txt
file5 $.txt

The same loops will not work and will error out. So you have to treat them like so:

cat listB.txt | while read i; do
   FILE=$(printf "%q" "$i")
   eval dosomething "$i"
done

Note: do not put quotes around the eval.

This will then properly process the files as it will naturally escape them.
It will properly run dosomething against those 5 files.

How does it do that? You can print out the FILE variable to understand. It simply backslashes (escapes) all of the special characters.

cat listB.txt | while read i; do
   FILE=$(printf "%q" "$i")
   echo "$FILE"
   echo ""
done

Output:

$ cat listB.txt | while read i; do printf "%q" "$i"; echo; done;
file1.txt
file2.txt
file3\ \"dot\ text\".txt
file4\ \"\'dot\ text.txt
file5\ \$.txt

Sidenote: from talking with others, nohup dosomething &> whatever &  can be weird if dosomething has to operate on file with special characters. Instead its better to put it in the background and then just disown it, like so:

dosomething &> whatever &
disown

 

The end.

Leave a Reply

Your email address will not be published. Required fields are marked *