문제

If I have this on the command line:

bin/my_file --name "this name with whitespace" dir/some_file

Then in my script:

full_cmd="$@"
# later...
"$full_cmd"

The quotation marks are not preserved. This is the closest I've come:

 app=$1
 shift
 $app "$@"

However, it would be convenient if it were possible to save the "$@" into a variable to re-use later, like this:

 my_func () {
    $app "$args"
 }

I haven't been able to make any of that work... other than messy for loops. I'm new to bash. I've search all other possible solutions and can't figure out why this is so hard. Am I missing something obvious?

도움이 되었습니까?

해결책 2

@choroba answer is good but you need to know that $0 is not in $@. As well here is an alternative:

printf -v myvar '%q ' "$@"

Then you have the strings shell escaped and thus will be correctly interpreted as separate arguments. And let me not forget - you need to use eval for invoking the command from the variables!

btw here $myvar is a normal string variable. It is not an array like in the above case. It is just that separate arguments are shell escaped with spaces in between.

Hope this helps.

Resources:

다른 팁

$@ is an array. Store it in an array:

ar=("$@")
"${ar[@]}"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top