How to change a command line argument in Bash?

Sriram picture Sriram · Jan 28, 2011 · Viewed 49.5k times · Source

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"

Answer

thkala picture thkala · Jan 28, 2011

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}".