Wildcards in file input to a script?

I have four files:

test
test2
test3
test4

I have this simple script:

#!/bin/bash
ls $1

Why does ./the_script.sh test* only list the first file, when a normal ls test* would list all four? What do I need to change in the script to be able to use wildcard?

Because test* is expanded to test, test1, test2, test3, etc., where $1 is test. $@, not $1, would list all the files beginning with "test".

The * character needs to be escaped:

./the_script.sh test\*
test  test2  test3  test4

I assume I could get that into a for loop...?

And best to put $@ in double quotes:

ls "$@"

Yes, you could do that.

$ cat myScript
for F in "$@"; do
  echo $F
done

$ ls filename*
filename1	filename2	filename3

$ ./myScript filename*
filename1
filename2
filename3

What if would do kind of the same thing but with grep, where I would use multiple arguments, and still wanted to use wildcard for the filenames?

I don't understand your question.

Sorry, that could be described a bit better, yes.

What if I would want to do this in a script:

grep string file*

This would obviously not work then, as it would only grep in one file?

#!/bin/bash
grep $1 $2

grep string file* would work (assuming "file*" doesn't expand to too many files).

If you want to do this from the command line, then:

$ ./myScript "some string to search for" file*

$ cat myScript
STR=$1
shift
grep "$STR" "$@"

Thanks, that works like a charm. :slight_smile: What does shift do?

shift = move along, nothing to see here :smiley:

$ cat myScript
echo $1 $2 $3
shift # get rid of first argument ($1)
echo $1 $2 $3

$ ./myScript A B C
A B C
B C

Ah, nice. :slight_smile: