Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

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

I would like to define a simple abbreviation of a call to gs (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):

#!/bin/sh
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 or myscript *.pdf outfile.pdf.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 whitespace.

So if you had this in your script:

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

And you called your script like this:

myscript out.pdf foo.ps bar.ps "another file.ps"

This would expand to:

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOUTPUTFILE=out.pdf foo.ps bar.ps "another file.ps"

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...