1

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"
done

but when I run this, I get

$ ./stuff.sh PRM*
./PRM.EDTOUT.ZIP

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?

2
  • 2
    When you run ./stuff.sh PRM*, bash will expand the glob and run ./stuff.sh PRM.EDTOUT.ZIP PRM.other.matches.zip. Your script never sees the pattern, it should just loop over all the arguments (for entry in "$@"; do .. or just for entry; do ) Commented Aug 5, 2016 at 20:42
  • Try ./stuff.sh "PRM*". You can also change your script to be a single line: ls $1 but you'll still have to quote your input so it doesn't get expanded before the script gets ahold of it. Commented Aug 5, 2016 at 20:43

1 Answer 1

4

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"
done

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"
done
Sign up to request clarification or add additional context in comments.

2 Comments

One point in favor of passing a quoted pattern: argument length. The command line that results from ./stuff.sh PRM* is limited in size; if the pattern matches too many files, you'll get a "Argument list too long" error. bash built-in commands, like the for loop, aren't subject to that limit. Compare echo {1..100000} with /bin/echo {1..100000} to see the difference. (Depending on your system, a larger upper bound may be sufficient, or you may need to increase it.)
The correct syntax is for entry do without a semi-colon. See stackoverflow.com/questions/36896830/…

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.