Home > Back-end >  Bash shell iterating through directory doesn't work as expected
Bash shell iterating through directory doesn't work as expected

Time:11-24

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related