Idiomatic way to exit ksh while loop

2019-07-23 19:45发布

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.

2条回答
我命由我不由天
2楼-- · 2019-07-23 20:23

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...."
查看更多
smile是对你的礼貌
3楼-- · 2019-07-23 20:46

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

timer() {
  i=0
  while (( ++i <= 5 )); do
    sleep 1
    printf '*'
  done
}
查看更多
登录 后发表回答