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?
Scott
November 9, 2012, 2:09pm
2
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
scott:
Because test* is expanded to test, test1, test2, test3, etc., where $1 is test. $@, not $1, would list all the files beginning with "test".
I assume I could get that into a for loop...?
And best to put $@ in double quotes:
ls "$@"
Scott
November 9, 2012, 2:20pm
6
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?
Scott
November 9, 2012, 2:28pm
8
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
Scott
November 9, 2012, 2:37pm
10
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" "$@"
scott:
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. What does shift do?
Scott
November 9, 2012, 2:46pm
12
shift = move along, nothing to see here
$ 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