Question

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?

Was it helpful?

Solution

You can preserve the $@ into a BASH array:

args=("$@")

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top