Joseph
Joseph

Reputation: 43

Bash shell iterating through directory doesn't work as expected

I am trying to iterate through a directory but the for loop doesn't work as expected. Look at this:

for dirname in "/dir_example/*"; do
    echo "$dirname"
done

What happens is that it only echos the string "/dir_example/*" and do not iterate over the directories. I tried it on another server and it worked. The shell is bash on the same computers. How is it possible?

Upvotes: 0

Views: 720

Answers (2)

Joseph
Joseph

Reputation: 43

Sorry man, I found my mistake. There was a typo in the directory name on the different server (a directory that didn't exist), that's why the echo printed the string.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 362037

Globs like * are only expanded if they're unquoted. Luckily you can drop in and out of quotes in the same word:

for dirname in "/dir_example"/*; do
    echo "$dirname"
done

Upvotes: 1

Related Questions