![嵌套 While 循环未按预期工作](https://linux22.com/image/103017/%E5%B5%8C%E5%A5%97%20While%20%E5%BE%AA%E7%8E%AF%E6%9C%AA%E6%8C%89%E9%A2%84%E6%9C%9F%E5%B7%A5%E4%BD%9C.png)
我编写了以下脚本:
CODE=`cut -c 7-21 Data.txt`
for i in ${CODE};
do
WIN=2
PER=50
if [ -f ../FASTA_SEC/${i}.fa ]
then
while [[ ${WIN} -lt 20 ]]
do
echo "The value of WIN is" $WIN "now begins nested while"
while [[ ${PER} -lt 100 ]]
do
echo "value of PER is" $PER
((PER=$PER+2))
done
((WIN=$WIN+2))
done
else
echo "the file does not exist" ${i}
fi
done
我期望它像这样工作:
$WIN $PER
2 50
2 52
2 54
2 56
[.....]
4 50
4 52
4 54
4 56
依此类推..我虽然可以用嵌套的 while 来做到这一点,但我得到以下结果:
The value of WIN is 2 now begins nested while
value of PER is 50
value of PER is 52
value of PER is 54
value of PER is 56
value of PER is 58
value of PER is 60
value of PER is 62
value of PER is 64
value of PER is 66
value of PER is 68
value of PER is 70
value of PER is 72
value of PER is 74
value of PER is 76
value of PER is 78
value of PER is 80
value of PER is 82
value of PER is 84
value of PER is 86
value of PER is 88
value of PER is 90
value of PER is 92
value of PER is 94
value of PER is 96
value of PER is 98
The value of WIN is 4 now begins nested while
The value of WIN is 6 now begins nested while
The value of WIN is 8 now begins nested while
The value of WIN is 10 now begins nested while
The value of WIN is 12 now begins nested while
The value of WIN is 14 now begins nested while
The value of WIN is 16 now begins nested while
The value of WIN is 18 now begins nested while
当 WIN 值为 2 时,内循环只运行一次,然后写入 win 值。为什么它没有按预期工作?
我如何将变量定义为增量为 2 的范围。例如,$PER=(Range 50:100, 2) 左右将此范围集成到for i in $PER loop
你有什么建议?
谢谢
答案1
您期望$PER
外循环每次迭代时该值都会重置为 50 while
,但您不会在那里重置它。
我还注意到您可能将大量数据读取到脚本顶部的单个变量中。
这会更有效(假设bash
或ksh
语法):
cut -c 7-21 "Data.txt" |
while read -r code; do
if [[ ! -f "../FASTA_SEC/$code.fa" ]]; then
printf 'No such file: %s\n' "../FASTA_SEC/$code.fa"
continue
fi
for (( win = 2; win < 20; win += 2 )); do
printf 'The value of win is %d, now entereing inner loop\n' "$win"
for (( per = 50; per < 100; per += 2 )); do
printf 'Value of per is %d\n' "$per"
done
done
done
这避免了将 的完整输出读cut
入变量,而是逐行读取。
它还避免了繁琐的while
循环。