我就是做不到。
脚本有两个参数:目标和命令。有效目标在数组中指定。如果目标是“全部”,脚本应迭代所有目标。
#!/bin/bash
# recur.sh
targets=('aaa' 'bbb' 'ccc' 'ddd')
if [ "$1" == "all" ] ; then
for i in $targets ; do
echo $2" --> "$i
./$0 $i $2
done
exit 0
fi
echo "Target "$1" just received command '"$2"'"
exit 0
我期望以下输出:
$ recur all boggle
boggle --> aaa
Target aaa just received command 'boggle'
boggle --> bbb
Target bbb just received command 'boggle'
boggle --> ccc
Target ccc just received command 'boggle'
boggle --> ddd
Target ddd just received command 'boggle'
但脚本在第一次迭代时退出:
$ recur all boggle
boggle --> aaa
Target aaa just received command 'boggle'
答案1
问题不在于递归,而在于循环项目。如果您按照上面的方法尝试,您将不会得到您所期望的结果:
$ targets=(aaa bbb ccc ddd)
$ for i in $targets; do echo $i; done
aaa
要循环数组,您需要生成数组中项目的列表,例如,这个链接:
所以你有了
#!/bin/bash
# recur.sh
targets=('aaa' 'bbb' 'ccc' 'ddd')
if [ "$1" == "all" ] ; then
for i in ${targets[@]}; do
echo $2" --> "$i
./$0 $i $2
done
exit 0
fi
echo "Target "$1" just received command '"$2"'"
exit 0
答案2
其他人已经指出,访问列表时使用的语法存在问题。但这并不是您的脚本的唯一问题。您还使用了不带引号的变量。当不带引号使用时$variablename
,如果该变量包含 shell 可以解释的任何字符,您将得到意外的结果。
以下是我将如何更改脚本以避免此类问题:
#!/bin/bash
# recur.sh
targets=('aaa' 'bbb' 'ccc' 'ddd')
if [ "$1" == "all" ] ; then
for i in "${targets[@]}"; do
echo "$2 --> $i"
"$0" "$i" "$2"
done
exit 0
fi
echo "Target $1 just received command '$2'"
exit 0
您应该养成总是将变量的用法放在双引号内的习惯,除非您有充分的理由不这样做。
答案3
问题是,您没有循环遍历数组中的所有元素,而只是循环遍历一个元素,因为您使用了$targets
而不是${targets[@]}
.
尝试这个修复:
targets=('aaa' 'bbb' 'ccc' 'ddd')
if [ "$1" == "all" ] ; then
for i in ${targets[@]} ; do
echo $2" --> "$i
echo "Target "$i" just received command '"$2"'"
done
fi
exit 0
这里不需要递归。