Magicloud
Magicloud

Reputation: 857

How to deal with file name starts with spaces in bash?

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?

Upvotes: 2

Views: 118

Answers (3)

user2599522
user2599522

Reputation: 3215

You can always use find with print

find ./ -print | xargs echo

Upvotes: 0

user2599522
user2599522

Reputation: 3215

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)

Upvotes: 0

anubhava
anubhava

Reputation: 785126

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' *

Upvotes: 7

Related Questions