从昨天开始,我就遇到了 shell 代码的奇怪行为。
这是代码:
#!/bin/bash
operatori="/*-+="
temp=$1
len_temp=${#temp}
for (( i=0; i<$len_temp; i++ ))
do
array[i]=${temp:i:1}
#echo 'i= '${array[i]}
done
for i in ${array[@]}
do
if [[ "$operatori" =~ "$i" ]]; then
echo '@@'$i
fi
done
它是用 $1 = tom*jerry-1=0
执行的。
在这个版本的代码中,我希望返回:
@@*
@@-
@@=
但它只返回
@@-
@@=
另一方面,我试图否认这个条件,有
if ! [[ "$operatori" =~ "$i" ]]; then
但结果比较奇怪:
@@t
@@o
@@m
@@analyzer.sh
@@gnome-terminal.desktop
@@mount location.sh
@@test.sh
@@j
@@e
@@r
@@r
@@y
@@1
@@0
我希望收到的地方:
@@t
@@o
@@m
@@j
@@e
@@r
@@r
@@y
@@1
@@0
其中 analyzer.sh、gnome-teminal.desktop、mount location.sh、test.sh 代表我的代码保存位置中的一些文件。
谁能告诉我我做错了什么?
最佳答案
您应该将变量引用括在双引号中以防止意外的解析异常。特别是,使用 for i in "${array[@]}"
和 echo "@@$i"
。
这里发生的事情是,在 for
语句中,数组扩展为等同于 t o m * j e r r y - 1 = 0
,然后进行分词(ok in这种情况下)和通配符扩展(用当前目录中的文件列表替换 *
),相当于 t o m analyzer.sh gnome-terminal.desktop 'mount location.sh ' test.sh j e r r y - 1 = 0
,这会导致您看到的奇怪结果。
您可以通过设置 noglob
shell 选项(如 Kenavoz 所建议的那样)来避免此问题),但这会破坏依赖于通配符扩展的脚本的任何部分(并且仍然会留下意想不到的可能性)分词)。最好只使用双引号。
关于linux - 解析数组时的异常行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37495567/