Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate all arguments and wrap them with double quotes

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?

like image 465
rui Avatar asked Jun 23 '10 17:06

rui


4 Answers

@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"
like image 71
glenn jackman Avatar answered Nov 17 '22 14:11

glenn jackman


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"
like image 24
Fritz G. Mehner Avatar answered Nov 17 '22 12:11

Fritz G. Mehner


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"
like image 3
ninjalj Avatar answered Nov 17 '22 13:11

ninjalj


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.

like image 3
msw Avatar answered Nov 17 '22 14:11

msw