gpt4 book ai didi

shell - 如何在 Bourne shell 的变量中存储带引号的字符串列表? (没有 Bash 数组)

转载 作者:行者123 更新时间:2023-12-05 00:18:17 31 4
gpt4 key购买 nike

使用 Bash's arrays ,我可以将列表存储到数组变量中并迭代元素,同时将包含空格或特殊字符的带引号的字符串保存在一起:

LIST=(--foo --bar --baz "test 1 2 3")
for item in "${LIST[@]}"; do
echo "$item"
done

输出是:
--foo
--bar
--baz
test 1 2 3

我有一个使用此功能的脚本,但不幸的是需要将其移植以使用 Busybox 的 ash(不支持数组)。我试图找出一种存储列表的好方法,其中某些项目可能会有空格,同时仍然保留列表中正确数量的元素。

这不起作用,例如(错误地将 test 1 2 3 拆分为单独的项目):
LIST='--foo --bar --baz "test 1 2 3"'
for item in $LIST; do
echo "$item"
done

输出是:
--foo
--bar
--baz
"test
1
2
3"

idea I found on the Busybox mailing list是使用 set --替换位置参数:
set -- --foo --bar --baz "test 1 2 3"
for item in "$@"; do
echo "$item"
done

输出正确:
--foo
--bar
--baz
test 1 2 3

但是,此构造破坏了此脚本也使用的位置参数列表 ( $@ )。

有没有什么合理的方法可以让我吃蛋糕,也可以吃它,并在非 Bash 中模拟多个任意数组 sh变种?

最佳答案

你可以用 \n 声明一个变量在里面:

list='--foo\n--bar\n--baz\n"test 1 2 3"'

# then iterate it using
echo -e "$list" | while read -r line; do echo "line=[$line]"; done

输出:
line=[--foo]
line=[--bar]
line=[--baz]
line=["test 1 2 3"]

关于shell - 如何在 Bourne shell 的变量中存储带引号的字符串列表? (没有 Bash 数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38210226/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com