Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting bash-quoted array from bash

In bash (possibly using commands commonly installed on a Unix system) I want to output all elements in an array to the terminal in such a way that each element of the array is a correctly quoted bash string.

For example, say the array contains three elements (I'll list them here one array element per line to avoid us getting confused about whether the quotes are part of the string):

foo
qux bar
wibble 'smoo' "blep"

Ideally I want to output:

foo "qux bar" "wibble 'smoo' \"blep\""

However, if it makes the implementation considerably simpler, I could also accept:

"foo" "qux bar" "wibble 'smoo' \"blep\""

Or even this:

foo qux\ bar wibble\ \'smoo\'\ \"blep\"

To be clear, I am aware of what happens when $@ is placed in quotes. For example:

echo "$@"

However, this is insufficient because, although quoting "$@" causes the array to be expanded with quotes around each item, those quotes aren't output, ie we get:

foo qux bar wibble 'smoo' "blep"

My intention here is that, I want a bash script to output a command line, which can then be copied and pasted back into a shell, without the arguments getting broken up incorrectly if they contain quotes/spaces. If the output looks "nice" - it has the same format that a user would generally use (avoiding quotes etc where unnecessary) - that's a bonus, but my main aim is robustness.

Obviously, one solution is to loop over the array, detect spaces and quotes, escape them as needed, surround with quotes. But re-implementing bash escaping rules inside bash feels a bit dirty (and potentially error prone) - so I'm wondering if I am missing some mechanism by which I can ask bash to do this for me.

like image 203
user3645242 Avatar asked May 16 '14 16:05

user3645242


1 Answers

Your last example of expected output is the exact output of

$ arr=( foo "quz bar" "wibble 'smoo' \"blep\"")
$ printf "%q " "${arr[@]}"
foo quz\ bar wibble\ \'smoo\'\ \"blep\"

The %q placeholder in printf outputs its string in quoted form, ready for use as input.

like image 185
chepner Avatar answered Nov 02 '22 06:11

chepner