简体   繁体   中英

How to change a command line argument in Bash?

Is there a way to change the command line arguments in a Bash script? For example, a Bash script is invoked like this:

./foo arg1 arg2  

Is there a way to change the value of arg1 within the script? Something like:

$1="chintz"

You have to reset all arguments. To change eg $3 :

$ set -- "${@:1:2}" "new" "${@:4}"

Basically you set all arguments to their current values, except for the one(s) that you want to change. set -- is also specified by POSIX 7 .

The "${@:1:2}" notation is expanded to the two (hence the 2 in the notation) positional arguments starting from offset 1 (ie $1 ). It is a shorthand for "$1" "$2" in this case, but it is much more useful when you want to replace eg "${17}" .

优化易读性和可维护性,您最好将$1$2分配给更有意义的变量(我不知道, input_filename = $1output_filename = $2或其他),然后覆盖这些变量之一( input_filename = 'chintz' ) ,保持脚本的输入不变,以防其他地方需要它。

I know this is an old one but I found the answer by thkala very helpful, so I have used the idea and expanded on it slightly to enable me to add defaults for any argument which has not been defined - for example:


    # set defaults for the passed arguments (if any) if not defined.
    #
    arg1=${1:-"default-for-arg-1"}
    arg2=${2:-"default-for-arg-2"}
    set -- "${arg1}" "${arg2}"
    unset arg1 arg2

I hope this is of use to someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM