process wildcards in bash scripts
I just need a simple example of a bash script to proccess a single file or multiple files if wildcard is passed as arguments
if I run
myscript file1do something with file, and if I issue
myscript *.pdfdo something with file matching criteria
Can anybody give a simple example?
2 Answers
The *.pdf will be expanded by the shell before executing the script, so the script won't see *.pdf, it will see the matching filenames directly:
$ cat foo.sh
#! /bin/sh
printf "|%s|\n" "$@"
$ touch {1..10}.pdf
$ ./foo.sh 1.pdf
|1.pdf|
$ ./foo.sh *.pdf
|1.pdf|
|10.pdf|
|2.pdf|
|3.pdf|
|4.pdf|
|5.pdf|
|6.pdf|
|7.pdf|
|8.pdf|
|9.pdf|Within a bash script, you can use "$@" to get all the arguments passed to it, or use $1, $2, etc. to access the first, second, etc. argument directly.
You can just loop over all arguments with a plain for:
for i # Or, for i in "$@"
do echo "Processing argument $i"
doneWill output:
Processing argument 1.pdf
Processing argument 10.pdf
Processing argument 2.pdf
Processing argument 3.pdf
Processing argument 4.pdf
Processing argument 5.pdf
Processing argument 6.pdf
Processing argument 7.pdf
Processing argument 8.pdf
Processing argument 9.pdf 1 Here is one reading in your file(s) as an array allowing you to work with it as you please:
#!/bin/bash
filearray=( "$@" )
if [ ${#filearray[@]} -gt "1" ] || [ ${#filearray[@]} == "0" ]; then isare=are ent=entries
else isare=is ent=entry
fi
echo "There $isare ${#filearray[@]} $ent."
echo ""
if [ ${#filearray[@]} == "0" ]; then echo "Nothing entered." exit
else echo "This is what you entered or what was found: " echo "" printf '%s\n' "${filearray[@]}"
fiUsing the "" for the array makes it so that it will read files even if they have spaces and won't separate them when they print. I also added wording changes based on the number of files found. No entry will show 0. The ${#filearray[@]} counts the number of elements, where ${filearray[@]} will show all elements.
Examples:
One entry:
$ ./myscript myfile.txt
There is 1 entry.
This is what you entered or what was found:
myfile.txtMultiple entries:
$ ./myscript *.sh
There are 5 entries.
This is what you entered or what was found:
blue-ray_encode.sh
lightsOn.sh
removeoffender.sh
test1.sh
test.shNo entries:
$ ./myscript
There are 0 entries.
Nothing entered.