Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle special characters in bash for...in loop

Suppose I've got a list of files

file1
"file 1"
file2

a for...in loop breaks it up between whitespace, not newlines:

for x in $( ls ); do
   echo $x
done

results:

file
1
file1
file2

I want to execute a command on each file. "file" and "1" above are not actual files. How can I do that if the filenames contains things like spaces or commas?

It's a little trickier than I think find -print0 | xargs -0 could handle, because I actually want the command to be something like "convert input/file1.jpg .... output/file1.jpg" so I need to permutate the filename in the process.

like image 703
ʞɔıu Avatar asked Dec 22 '22 08:12

ʞɔıu


2 Answers

Actually, Mark's suggestion works fine without even doing anything to the internal field separator. The problem is running ls in a subshell, whether by backticks or $( ) causes the for loop to be unable to distinguish between spaces in names. Simply using

for f in *

instead of the ls solves the problem.

#!/bin/bash
for f in *
do
 echo "$f"
done
like image 149
Jordan Avatar answered Jan 03 '23 23:01

Jordan


UPDATE BY OP: this answer sucks and shouldn't be on top ... @Jordan's post below should be the accepted answer.

one possible way:

ls -1 | while read x; do
   echo $x
done

like image 31
eduffy Avatar answered Jan 04 '23 00:01

eduffy