我正在尝试编写一个简单的脚本,该脚本会运行几个命令 N 次,具体次数由用户输入决定。但是,当运行命令时(在 for 循环中) - 变量会被忽略:
read -p "Please enter the number of times you wish to fail over: " num
...
for run in {1..$num}
do echo "STOP: "
date
systemctl stop $broker
date
sleep $st
echo "START: "
date
systemctl start $broker
date
sleep $st
done
fi
+ '[' y == n ']'
+ '[' y == N ']'
+ for run in '{1..$num}'
+ echo 'STOP: '
STOP:
+ date
Tue Dec 4 16:14:11 GMT 2018
谁能解释为什么会发生这种情况以及我需要做什么来纠正?或者有人有更好的方法吗?
答案1
只是一些或多或少安全且可能众所周知的方法的集合:
a=5
eval "for i in {1..$a}; do echo \$i; done"
cat <<< "for i in {1..$a}; do echo \$i; done" | bash
echo "for i in {1..$a}; do echo \$i; done" | bash
for i in $(seq 1 $a); do echo $i; done