简体   繁体   English

从bash输出bash引用的数组

[英]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. 在bash中(可能使用通常安装在Unix系统上的命令)我希望将数组中的所有元素输出到终端,使得数组的每个元素都是正确引用的bash字符串。

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. 我的意图是,我想要一个bash脚本输出一个命令行,然后可以将其复制并粘贴回shell,如果它们包含引号/空格,则参数不会被错误地分解。 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. 但是在bash中重新实现bash转义规则感觉有点脏(并且可能容易出错) - 所以我想知道我是否缺少一些机制,我可以通过它来请求bash为我做这个。

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. printf%q占位符以引用形式输出其字符串,可以用作输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM