4

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?

9

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"
done

Will 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
  • to be thourough: it won't see the pattern IF there is at least 1 file matching that pattern? But if there are no *.pdf files in the current directory of the person typing script *.pdf, the script will indeed receive *.pdf as the shell couldn't replace it with any filenames. And one can pass *.pdf by putting it inside quotes ( "*.pdf" or '*.pdf' ) or escaping the * ( \*.pdf ) – Olivier Dulac May 17 '17 at 14:15
3

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[@]}"
fi

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:

$ ./myscript myfile.txt
There is 1 entry.

This is what you entered or what was found: 

myfile.txt

Multiple 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.sh

No entries:

$ ./myscript 
There are 0 entries.

Nothing entered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.