2

good day, I am creating a script to read one level of subfolders/directories of a path. The script is like so:

#loopdir.sh
for i in `ls -d $1`
do
echo $i
done

But when I tried to use it to read /media/My\ Passport/, it reads the argument as two different dirs:

$ ./loopdir.sh /media/My\ Passport/
ls: cannot access /media/My: No such file or directory
Passport/
2
  • other ref: linux.byexamples.com/archives/314/… Commented Feb 28, 2013 at 10:01
  • Thank you @kepinpin for un-accepting my wrong answer. Now, I can delete it... :-) Commented Feb 19, 2016 at 14:22

3 Answers 3

5

Try doing this instead (my understanding is that you want to list subdirs, Am I right?) :

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

Parsing ls output is a bad idea : it's is a tool for interactively looking at file information. Its output is formatted for humans and will cause bugs in scripts. Use globs or find instead. Understand why: http://mywiki.wooledge.org/ParsingLs

And (last but not least) : USE MORE QUOTES! They are vital. Also, learn the difference between ' and " and `. See http://mywiki.wooledge.org/Quotes and http://wiki.bash-hackers.org/syntax/words

Sign up to request clarification or add additional context in comments.

1 Comment

I want to second this consideration of parsing ls. It is widely known for containing black magic that can break what you are doing.
1

You need to surround your $i with quotes: echo "$i"

5 Comments

sorry, I've just tried it, no dice. The output is still: ls: cannot access /media/My: No such file or directory Passport/
Why the backslash in your filename?
This is going to bother me all night.
There is no backslash in filename. It has been added by bash, to escape space between My & Passport.
Quoting won't help, as there's nothing that needs to be quoted in $1; the space is used by the shell for wordsplitting before $i's value is set.
0

don't $i

this will break by space

using "$i"

1 Comment

It's too late to quote the variable after you try to iterate over the ouptut of ls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.