退出Ksh While循环的惯用方式 [英] Idiomatic way to exit ksh while loop
本文介绍了退出Ksh While循环的惯用方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下5秒钟的计时器,它每秒钟打印一个星号.
I've the following 5 second timer which prints an asterisk for each second.
timer () {
i=1
trap 'i=5' INT
while [[ $i -le 5 ]]; do
sleep 1
printf "*"
((i+=1))
done
}
不知何故,陷阱块似乎有点怪异,我想知道是否有更正确的方法来中断整个循环(而不仅仅是当前的睡眠周期).我尝试过:
Somehow the trap chunk seems a little hackish and I wonder if there's a more correct way to interrupt the entire loop (not just the current sleep cycle). I've tried:
trap 'print "foo"' INT
函数内部和外部的不同位置,但是正如我之前提到的那样,这只是中断了当前的睡眠周期.
at various locations inside and outside the function, but as I alluded to before, that just interrupts the current sleep cycle.
推荐答案
在bash中对我有用:
This works for me in bash:
#!/bin/bash
function timer {
trap "break" INT
i=0
while (( ++i <= 5 )); do
sleep 1
printf '*'
done
}
echo "Starting timer"
timer
echo "Exited timer"
echo "Doing other stuff...."
,这在ksh中(请注意trap语句的不同位置):
and this in ksh (note the different location of the trap statement):
#!/bin/ksh
function timer {
trap "break" INT
i=0
while (( ++i <= 5 )); do
sleep 1
printf '*'
done
}
echo "Starting timer"
timer
echo "Exited timer"
echo "Doing other stuff...."
这篇关于退出Ksh While循环的惯用方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文