Outputting a bash -quoted array from bash

In bash (possibly using commands usually installed on a Unix system), I want to output all the elements in the array to the terminal so that each element in the array correctly quotes the bash string.

For example, let's say that the array contains three elements (I listed them here one element of the array per string, so as not to confuse about whether the quotation marks are part of the string):

foo
qux bar
wibble 'smoo' "blep"

Ideally, I want to output:

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

However, if this greatly simplifies the implementation, I can also accept:

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

Or even this:

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

To be clear, I know what happens when $ @ is put in quotation marks. For instance:

echo "$@"

However, this is not enough, because although quoting "$ @" causes the array to expand with quotes around each element, these quotes are not displayed, i.e. we get:

foo qux bar wibble 'smoo' "blep"

, , bash script , ​​ , , , /. "" - , ( .., ) - , - .

, , , , . bash escaping bash ( ) ​​- , - , bash .

+4
1

-

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

%q printf , .

+8

Source: https://habr.com/ru/post/1540868/


All Articles