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 file1
do something with file, and if I issue
myscript *.pdf
do something with file matching criteria
Can anybody give a simple example?
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: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
:Will output:
Here is one reading in your file(s) as an array allowing you to work with it as you please:
Using 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:
Multiple entries:
No entries: