문제

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.

올바른 솔루션이 없습니다

다른 팁

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

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

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...."
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top