I'm coding up a sort of custom rm script that I would like to pass wildcard matches to. I have several files in the working directory that would match the wildcard that I'm passing to the script, but I'm only getting one of them back from a simple test case:
sh remove r*
Inside the remove script, I've whittled it down to just
echo $1
Here's the directory contents:
$ ls
file2 file4 newTestFile remove_engine restore
file3 fileName_1234 remove remove_w restore_engine
And here's what I get back.
$ sh remove r*
remove
I understand that BASH expands the wildcard out even before the script is executed. But why am I not getting all of the files in the directory that match f*?
Pathname expansion, aka globbing, expands a single shell word into multiple. In your case
./remove r*
is entirely identical to running
./remove remove remove_engine restore remove remove_w restore_engine
As you discovered, $1 will be remove because this is the first argument. The rest of the files are separate positional parameters, so $2 will be remove_engine and $3 will be restore.
To process all of the arguments, you use "$@", either in a loop:
for file in "$@"
do
printf 'One of the matches was: %s\n' "$file"
done
or just directly in commands that also accept multiple parameters:
# Delete all matches
echo rm "$@"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With