Idiomatic way to exit ksh while loop

假装没事ソ 提交于 2019-12-13 00:14:51

问题


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.


回答1:


Perhaps I'm missing something, but what's wrong with:

timer() {
  i=0
  while (( ++i <= 5 )); do
    sleep 1
    printf '*'
  done
}



回答2:


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...."

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...."


来源:https://stackoverflow.com/questions/8478374/idiomatic-way-to-exit-ksh-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!