views:

75

answers:

5
function foo() {
A=$@...
echo $A
}

foo bla "hello ppl"

I would like the output to be:
"bla" "hello ppl"

What do I need to do instead of the ellipsis?

+2  A: 

You can use "$@" to treat each parameter as, well, a separate parameter, and then loop over each parameter:

function foo() {
for i in "$@"
do
    echo -n \"$i\"" "
done
echo
}

foo bla "hello ppl"
ninjalj
+1 This solution works! I am lazy, so I usually drop the 'in "$@"' part and only use 'for i'
Hai Vu
I forgot to mention this in the question but I meant to do this without using a loop. Was looking for some magic bash expansion or something.
ruibm
+2  A: 

ninjalj had the right idea, but the use of quotes was odd, in part because what the OP is asking for is not really the best output format for many shell tasks. Actually, I can't figure out what the intended task is, but:

function quote_args {
   for i ; do
      echo \""$i"\"
   done
}

puts its quoted arguments one per line which is usually the best way to feed other programs. You do get output in a form you didn't ask for:

$ quote_args this is\ a "test really"
"this"
"is a"
"test really"

but it can be easily converted and this is the idiom that most shell invocations would prefer:

$ echo `quote_args this is\ a "test really"`
"this" "is a" "test really"

but unless it is going through another eval pass, the extra quotes will probably screw things up. That is, ls "is a file" will list the file is a file while

$ ls `quote_args is\ a\ file`

will try to list "is, a, and file" which you probably don't want.

msw
+1  A: 

No loop required:

foo() { local saveIFS=$IFS; local IFS='"'; local a="${*/#/ \"}"; echo "$a"\"; IFS=$saveIFS; }

Saving IFS isn't necessary in this simple example, especially restoring it right before the function exits, due to the fact that local is used. However, I included it in case other things are going into the function that a changed IFS might affect.

Example run:

$ foo a bcd "efg hij" k "lll mmm nnn " ooo "   ppp   qqq   " rrr\ sss
 "a" "bcd" "efg hij" "k" "lll mmm nnn " "ooo" "   ppp   qqq   " "rrr sss"
Dennis Williamson
+2  A: 

Use parameter substitution to add " as prefix and suffix:

function foo() {
    A=("${@/#/\"}")
    A=("${A[@]/%/\"}")
    echo -e "${A[@]}"
}

foo bla "hello ppl" kkk 'ss ss'

Output

"bla" "hello ppl" "kkk" "ss ss"
fgm
+3  A: 

@msw has the right idea (up in the comments on the question). However, another idea to print arguments with quotes: use the implicit iteration of printf:

foo() { printf '"%s" ' "$@"; echo ""; }

foo bla "hello ppl"
# => "bla" "hello ppl"
glenn jackman
Ding! You win the big prize. Giant teddy bear or four-foot beer-bottle coin bank?
Dennis Williamson