Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 
like image 308
Sriram Avatar asked Jan 28 '11 11:01

Sriram


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do I run a command line argument in bash?

You can handle command-line arguments in a bash script in two ways. One is by using argument variables, and another is by using the getopts function.

How do you assign command line arguments in shell script?

Passing Arguments Using Flags and Options in Shell ScriptAn option is always followed by a value while flags are not followed by any value. First, we will make a new bash script that takes two different arguments (options) i.e. -n/--name for name, and -i/--id for an identification number.


1 Answers

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

like image 116
thkala Avatar answered Nov 07 '22 08:11

thkala