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

泄露秘密 提交于 2019-12-12 14:31:12

问题


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?


回答1:


You can preserve the $@ into a BASH array:

args=("$@")

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




回答2:


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.



来源:https://stackoverflow.com/questions/22117937/how-can-the-arguments-to-bash-script-be-copied-for-separate-processing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!