sh + 如何在 sh 脚本中使用数组以打印数组中的所有值

mai*_*ash 11 shell array shell-script

我想在我的sh脚本中使用数组

我的目标是创建一个包含值的数组a b c并打印数组中的所有值。

我成功打印了每个数组,但未能打印数组中的所有值。

下面的例子:

在 arr 中设置每个值

n=1
eval arr$n=a
n=2
eval arr$n=b
n=3
eval arr$n=c
Run Code Online (Sandbox Code Playgroud)

从 arr 打印每个值

n=1
eval echo \$arr$n
a
n=2
eval echo \$arr$n
b
n=3
eval echo \$arr$n
c
Run Code Online (Sandbox Code Playgroud)

现在我想打印所有值$arr而不是a b c我得到:

n="*"
eval echo \$arr$n
{*}*
Run Code Online (Sandbox Code Playgroud)

值应该是a b c

hjc*_*710 35

有点晚了,但我没有看到理想的sh答案在这里,所以我会附和。如果你不需要下标,然后sh有效地支持数组。它只是支持它们作为空格分隔的字符串。您可以打印它们的全部内容,“推送”给它们,或者很好地遍历它们。

这是一些示例代码:

NAMES=""
NAMES="${NAMES} MYNAME"
NAMES="${NAMES} YOURNAME"
NAMES="${NAMES} THEIRNAME"

echo 'One at a time...'
for NAME in ${NAMES}; do
    echo ${NAME};
done

echo 'All together now!'
echo ${NAMES}
Run Code Online (Sandbox Code Playgroud)

哪些输出:

One at a time...
MYNAME
YOURNAME
THEIRNAME
All together now!
MYNAME YOURNAME THEIRNAME
Run Code Online (Sandbox Code Playgroud)

现在,我说它不支持子脚本,但是通过一点点cut魔法并使用空格作为适当的分隔符,你绝对可以模仿它。如果我们将其添加到上面示例的底部:

echo 'Get the second one'
echo ${NAMES} | cut -d' ' -f2

echo 'Add one more...'
NAMES="${NAMES} TOM"

echo 'Grab the third one'
echo ${NAMES} | cut -d' ' -f3
Run Code Online (Sandbox Code Playgroud)

运行它,我们得到:

Get the second one
YOURNAME
Add one more...
Grab the third one
THEIRNAME
Run Code Online (Sandbox Code Playgroud)

这是我们所期望的!

但是,其中包含空格的字符串可能会导致问题,并会完全破坏子脚本。

所以,真正更好的说法是:数组是不明显的,sh并且处理带有空格的字符串数组很困难。如果您不需要这样做(例如,要部署到的主机名数组),那么sh它仍然是完成这项工作的好工具。


cuo*_*glm 9

sh不支持array,并且您的代码不会创建数组。它创建了三个变量arr1, arr2, arr3

要在类似kshshell 中初始化数组元素,您必须使用 syntax array[index]=value。要获取数组中的所有元素,请使用${array[*]}${array[@]}

尝试:

n=1
eval arr[$n]=a
n=2
eval arr[$n]=b
n=3
eval arr[$n]=c

n=1
eval echo \${arr[$n]}
n=2
eval echo \${arr[$n]}
n=3
eval echo \${arr[$n]}

n='*'

eval echo \${arr[$n]}
Run Code Online (Sandbox Code Playgroud)