2

Normally, example shows usage like:

for i in $(ls); do echo ${i}; done

But if there is a file (or directory) named " screw", then the above line will give out wrong result.

How to solve?

Magicloud
  • 818
  • 1
  • 7
  • 17
  • 1
    possible duplicate of [File names with spaces in BASH](http://stackoverflow.com/questions/3967707/file-names-with-spaces-in-bash) – Kamiccolo Nov 13 '13 at 08:16

3 Answers3

7

No please don't use/parse ls's output. Use it like this:

for i in *; do echo "${i}"; done

Alternatively you can use printf (thanks to @ruakh):

printf '%s\n' *
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    You can still use `printf "%s\n" "$i"` in the for loop, for cases where an explicit loop is required. – chepner Nov 13 '13 at 12:47
0
IFS="$(echo -e "\b\r")";
for f in $(ls); do
    echo "$f";
done

In case you are forced to stick to parsing ls output (which you shouldn't)

user2599522
  • 3,005
  • 2
  • 23
  • 40
  • Both backspace and carriage return, technically, are legal characters in file names (as are newlines, which this lets slip through), so one really shouldn't use `ls` like this, period. – chepner Nov 13 '13 at 12:48
0

You can always use find with print

find ./ -print | xargs echo
user2599522
  • 3,005
  • 2
  • 23
  • 40