#!/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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)