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
  • 820
  • 1
  • 7
  • 15
  • 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
  • 713,503
  • 59
  • 514
  • 593
  • 1
    +1, though for this exact example I think it would make more sense to write `printf '%s\n' *` rather than a `for`-loop. (That would also give better portability, since POSIX doesn't impose strong requirements on `echo`.) – ruakh Nov 13 '13 at 08:17
  • Thanks @ruakh: Edited and added printf also. – anubhava Nov 13 '13 at 08:19
  • 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
  • 2,779
  • 2
  • 20
  • 38
  • 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
  • 2,779
  • 2
  • 20
  • 38