Parsing/passing command line arguments to a bash s

2019-01-18 13:39发布

问题:

I am using a bash script to call and execute a .jar file from any location without having to constantly enter its explicit path.

The .jar requires additional variable parameters to be specified at execution, and as these can be anything, they cannot be hard coded into the script.

There are 3 variables in total, the first specifies 1 of 2 actions that the .jar is to make, the second specifies a target file to enact this action on and the third specifies the name of a file that the action is to create.

The script I am currently using is:

#!/bin/bash  
java -jar "C:\path\to\file.jar" "$1" "$2" "$3"

I know very little about bash scripting, but while searching for another answer to my woes (now fixed) I came across "$@" and "$*" when referencing command line arguments. Doing more searching brought me to this site: How To Wiki: How to read command line arguments in a bash script, but I can't find any solid information about those arguments without having to wade through tons of advanced bash programming that is way above my head.

So now that I have rambled on forever, my question is relatively simple:

Can I replace "$1" "$2" "$3" with "$@" or "$*", and if so which is the better one to use?

Also what, if any, is the difference between those commands?

回答1:

"$@" corresponds to "$1" "$2" "$3" etc. "$*" corresponds to "$1 $2 $3" which you do not seem to need.

Without quotes, there is no difference, they both correspond to $1 $2 $3 etc.



回答2:

$* is all parameters as a single word, $@ is all parameters as individual quoted string.

I usually ends up using "$@", seems to work the best for me.



回答3:

$* contains a single string composed of all of the arguments separated by the first character of $IFS. Thus, if you set IFS to contain a character that cannot usefully be present in your arguments (e.g. a newline if you're passing filenames), then you can consider $* and "$@" to be functionally equivalent, though they work differently under the hood.

$@ is essentially an array of all of the arguments. When passed in double quotation marks ("$@"), the shell individually wraps each value in the array with double quotes (making it an odd exception to the normal rule of double quotes wrapping the entire expansion of a variable).

IIRC, the behavior of a bare $@ without double quotes is not fully specified in the POSIX spec, so it should be considered undefined behavior. Thus, you should never use a bare $@ without double quotes.

BTW, if you care about System V prior to version 3, there were some ancient quirks in how they handled $@. These are largely of historical interest at this point, but they'll give you some appreciation of how the standard evolved as people ran into problems. :-)