Marius Hofert Marius Hofert - 2 years ago 67
Bash Question

How to define a shell script with variable number of arguments?

I would like to define a simple abbreviation of a call to

(ghostscript) via a shell script. The first argument(s) give all the files that should be merged, the last one gives the name of the output file. Obviously, the following does not work (it's just for showing the goal):

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOUTPUTFILE=$last $1 $2 ...

How can this be done?

One would typically call this script via
myscript infile1.pdf infile2.pdf ... outfile.pdf
myscript *.pdf outfile.pdf

Answer Source

The bash variables $@ and $* expand into the list of command line arguments. Generally, you will want to use "$@" (that is, $@ surrounded by double quotes). This will do the right thing if someone passes your script an argument containing.

So if you had this in your script:

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOUTPUTFILE=$outputfile "$@"

And you called your script like this:

myscript out.pdf "another"

This would expand to:

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOUTPUTFILE=out.pdf "another"

Read the "Special Parameters" section of the bash man page for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download