How to put all command arguments in one variable

I want to execute a shell script that requires 3 arguments.

Argument number 2 contains a space with a space

I want to put all the arguments in one variable as follows:

Linux:~# kk="\"111\" \"222 222\" \"333\"" Linux:~# echo $kk "111" "222 222" "333" 

Now, if I call the function:

 func() { echo ---$1--- echo ---$2--- echo ---$3--- } 

with the variable $ kk this way

 func $kk 

Then he will return

 Linux:~# func $kk ---"111"--- ---"222--- ---222"--- 

And I expected to get this result

 ---111--- ---222 222--- ---333--- 

How to solve this problem without using eval ?

I know that eval solves this problem, but I do not want to use it (since it takes a lot of time to make such a call).

+2
linux shell ash
source share
2 answers

OP is a originally tagged bash question, then remove the tag. Please contact Charles Duffy for an excellent POSIX shell solution! the solution below uses arrays and is suitable only for bash .


You should not put your data in a string like this, but in an array. By the way, you are missing some quotes in your function:

 func() { echo "---$1---" echo "---$2---" echo "---$3---" } 

or even better ( printf preferable to echo ):

 func() { printf -- '---%s---\n' "$1" printf -- '---%s---\n' "$2" printf -- '---%s---\n' "$3" } $ kk=( "111" "222 222" "333" ) $ func "${kk[@]}" 

will happily print:

 ---111--- ---222 222--- ---333--- 

You can include new lines in your arguments, etc.

 $ kk=( $'one\none' "222 222" $' * three\nthree' ) $ func "${kk[@]}" ---one one--- ---222 222--- --- * three three--- 
+3
source share

If functions (like arrays) didn't make bash more expressive than POSIX sh, then there would be no reason to add them. :)

However, you can work around this by overriding " $@ " for your needs:

 set -- 111 "222 222" 333 printf '%s\n' " $@ " 

... will print ...

 111 222 222 333 

If you need to gradually create an argument list, you can make several set calls with " $@ " as the first arguments (make sure you see quotation marks!):

 set -- 111 set -- " $@ " "222 222" set -- " $@ " 333 printf '%s\n' " $@ " 

... will print ...

 111 222 222 333 
+3
source share

All Articles