How to change a command line argument in Bash?

BashCommand Line-Arguments

Bash Problem Overview


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"

Bash Solutions


Solution 1 - Bash

You have to reset all arguments. To change e.g. $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 (i.e. $1). It is a shorthand for "$1" "$2" in this case, but it is much more useful when you want to replace e.g. "${17}".

Solution 2 - Bash

Optimising for legibility and maintainability, you may be better off assigning $1 and $2 to more meaningful variables (I don't know, input_filename = $1 and output_filename = $2 or something) and then overwriting one of those variables (input_filename = 'chintz'), leaving the input to the script unchanged, in case it is needed elsewhere.

Solution 3 - Bash

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSriramView Question on Stackoverflow
Solution 1 - BashthkalaView Answer on Stackoverflow
Solution 2 - BashJohnsywebView Answer on Stackoverflow
Solution 3 - Bashmr_thinkitView Answer on Stackoverflow