Kayla Jin Kayla Jin - 2 months ago 5x
Bash Question

bash shell script - list files of certain pattern specified in cmd line arg

I'm making a generic bash script whose input $1 is file pattern that it wants to iter through. Right now I have

for entry in ./$1; do
echo "$entry"

but when I run this, I get

$ ./stuff.sh PRM*

although there are many files of pattern PRM*. Is there a way to specify this pattern in the command line args and list correctly all files of the same pattern?


When you call ./stuff.sh PRM*, PRM* is expanded by the shell to the matching files. If you want to pass the pattern without expansion, then you have to quote it:

./stuff.sh 'PRM*'

But actually, it will be better to just let the shell expand it (don't quote it, use it as in your example), but change your script to take multiple arguments, like this:

for entry; do
  echo "$entry"

That's right, there is no "in" after for entry. None needed. The for loop uses the positional parameters by default in the absence of an "in" clause. In other words, the above is equivalent to this:

for entry in "$@"; do
  echo "$entry"