bash:从数组中删除变量?

标签 bash shell

<分区>

#!/bin/bash

tank=(one two three)
x=two

unset tank[${x}]
echo ${tank[*]}

我想从数组中删除 x 但不知何故它删除了数组的第一个元素。我该如何解决?

最佳答案

您有一个索引数组,因此 [...] 中的值被视为算术表达式以生成整数索引。这种表达式中的字符串被假定为参数名称,未定义的参数评估为零。由于 two 未定义,您的尝试被评估为

unset tank[${x}] -> unset tank[two] -> unset tank[0]

要从数组中安全地删除一个项目,您需要遍历整个数组,将不匹配的项目复制到一个新数组,然后将新数组重新分配给旧名称。这可以防止拆分可能包含空格的数组元素。

x=two
new_tank=()
for i in "${tank[@]}"; do
    if [[ $i != $x ]]; then
        new_tank+=("$i")
    fi
done
tank=( "${new_tank[@]}" )

更简洁,正如 gniourf_gniourf 所指出的:

for i in "${!tank[@]}"; do
    [[ ${tank[i]} = $x ]] && unset tank[i]
done

根据您的应用程序,您可能需要考虑使用关联数组。

declare -A tank
tank=([one]=1 [two]=2 [three]=3)   # Using the keys as the actually elements
x=two
unset tank[$x]
# Prove that two is really gone, with no hole left behind.
for i in "${!tank[@]}"; do
   echo "$i"
done

关于bash:从数组中删除变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20020129/

相关文章:

shell - Ubuntu Terminal vi编辑器中For Loop的语法错误

bash 脚本 : meaning of while read in a simple script that use inotifywait

regex - Bash 正则表达式在行开头匹配 "./"?或者使用前导 "-"重命名文件

bash - 在 bash 历史命令中包含路径 (pwd)

linux - 由于 While,读取命令无法按预期工作

linux - 创建特定范围内编号的 linux 文件夹列表

linux - 获取父级最后一个命令的退出状态

regex - 自定义 `git log` 并在 `@` 处截断作者电子邮件的最简单方法是什么?

mongodb - 将 kubectl exec 的返回值获取到 powershell 脚本中

shell - 如何在 ksh shell 脚本中计算前一个工作日?