Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the arguments to bash script be copied for separate processing?

There is an existing bash script I need to modify, but I want to encapsulate the changes required to it in a function without affect how it manipulates the '$@' variable.

My idea is to copy the argument string to a new variable and extract the arguments required separately, but it seems that applying the 'shift' operates only on the $@ variable and modifies it permanently.

Is there way to emulate the processing of the $@ variable and its related functions on a normal string?

like image 939
vfclists Avatar asked Mar 01 '14 17:03

vfclists


People also ask

How does bash parse arguments?

Bash scripts take in command-line arguments as inputs both sequentially and also, parsed as options. The command-line utilities use these arguments to conditionally trigger functions in a Bash script or selectively choose between environments to execute the script.

How do I pass multiple arguments in bash?

You can pass more than one argument to your bash script. In general, here is the syntax of passing multiple arguments to any bash script: script.sh arg1 arg2 arg3 … The second argument will be referenced by the $2 variable, the third argument is referenced by $3 , .. etc.


1 Answers

You can preserve the $@ into a BASH array:

args=("$@")

And construct/retrieve/process original arguments anytime from BASH array "${args[@]}"

like image 125
anubhava Avatar answered Nov 14 '22 22:11

anubhava