Reputation: 20211
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?
Upvotes: 8
Views: 3574
Reputation: 785186
You can preserve the $@
into a BASH array:
args=("$@")
And construct/retrieve/process original arguments anytime from BASH array "${args[@]}"
Upvotes: 14
Reputation: 1439
Your question is a bit vage, there is no code shown. So I just guess this may help:
#!/bin/bash
atline=$@
echo ---------- complete command line:
echo $atline
echo ---------- dissecting command line syntax 1
for e in $atline; do echo $e; done
echo ---------- syntax 2
for ee ; do echo $ee; done
The result of one run is:
strobel@suse131:~/bin> test.sh one two three "four and five"
---------- complete command line:
one two three four and five
---------- dissecting command line syntax 1
one
two
three
four
and
five
---------- syntax 2
one
two
three
four and five
As you see, one problem is parsing of arguments that contain spaces. One reason to never put spaces into file names.
Another possible solution:
the bash reference says The positional parameters are temporarily replaced when a shell function is executed
so you could isolate your code in a function.
I think shift
should not be used in bash scripts, there are better solutions as you can see.
Upvotes: 0