将数组输出存储到 bash 脚本中的逗号分隔列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38625176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store array output to comma separated list in bash scripting
提问by Rock26
I have taken input from user into array. But I need to use them as comma separated list. How can I do that? Input in my case is path like (/usr/tmp/). I appreciate your help and time. Thank you !
我已将用户的输入输入到数组中。但我需要将它们用作逗号分隔的列表。我怎样才能做到这一点?在我的情况下,输入是类似 (/usr/tmp/) 的路径。我感谢您的帮助和时间。谢谢 !
Example:
例子:
read "Number of subdirectories : " count
for i in $(seq 1 $count)
do
read -e -p " Subdir : $i: " arr[$i]
done
Expected Result:
预期结果:
$var = {arr[1],arr[2],arr[3],......}
回答by John1024
If you have an array like this:
如果你有一个这样的数组:
$ declare -p arr
declare -a arr='([1]="abc" [2]="def")'
You can display it in comma-separated format:
您可以以逗号分隔的格式显示它:
$ (IFS=,; echo "{${arr[*]}}")
{abc,def}
That output can be saved in a shell variable using command substitution:
可以使用命令替换将该输出保存在 shell 变量中:
$ var=$(IFS=,; echo "{${arr[*]}}")
$ echo "$var"
{abc,def}