我需要一种在"内执行相同命令的方法。循环,例如命令1。 实际上我需要这个,因为命令1非常长并且对于不同的变量应该执行类似的操作。
if [ $variable = 'all' ]; then
for host in "${servers[@]}"; do
command 1
done
elif [ $variable != 'all' ]; then
--->go to command 1
fi
答案 0 :(得分:2)
这就是函数的用途:代码重用
do_command1() {
local host=$1
command1 "$host" arg ...
}
if [ $variable = 'all' ]; then
for host in "${servers[@]}"; do
do_command1 "$host"
done
else
do_command1 def_host
fi
答案 1 :(得分:1)
创建一个公共数组进行迭代,根据$variable
设置其值:
if [[ $variable = 'all' ]]; then
my_arr=( "${servers[@]}" )
else
# You may need to provide a suitable value for the lone
# array element here, other than "dummy_host"
my_arr=( dummy_host )
fi
for host in "${my_arr[@]}"; do
command 1
done