shell 将数组的所有值用引号括起来

idfiyjo8  于 2022-12-13  发布在  Shell
关注(0)|答案(1)|浏览(174)

下面是一个例子:

arr1=("a" "b" "c" "d" "e" "f")

我想把数组显示为引号,所以echo的输出应该是:

AA_ENABLE_HOOKS=("a" "b" "c" "d" "e" "f")

我做了下面的代码它几乎显示我想要的,但我不喜欢它:

#!/bin/bash

arr1=("a" "b" "c" "d" "e" "f")

var_quote=$( printf "\"%s\" " "${arr1[@]}")

echo "AA_ENABLE_HOOKS=(${var_quote})"

输出为

AA_ENABLE_HOOKS=("a" "b" "c" "d" "e" "f" ) // notice I have space at the end

在bash中有我上面的代码的替代品吗?
我目前的单行命令解决方法是:

echo "AA_ENABLE_HOOKS=($( printf "\"%s\" " "${arr1[@]}" | sed -e 's/\ *$//g'))"
cdmah0mi

cdmah0mi1#

$ echo "AA_ENABLE_HOOKS=(${arr1[@]@Q})"
AA_ENABLE_HOOKS=('a' 'b' 'c' 'd' 'e' 'f')

请参见Shell参数扩展中的**${parameter@operator}**。这是在bash 4.4中引入的
或者,如果这是一种序列化技术:

$ declaration=$(declare -p arr1)
$ echo "${declaration/arr1/AA_ENABLE_HOOKS}"
declare -a AA_ENABLE_HOOKS=([0]="a" [1]="b" [2]="c" [3]="d" [4]="e" [5]="f")

相关问题