开发者

why doesn't this timer work?

I'm trying to make a script to start a second counter. [but later I want to add minutes too] but so far, it just keeps echoing 0, 0, 0, 0, over and over. :\

#!/bin/bash
seconds=0;
count()
开发者_如何学编程{
export seconds=$[seconds + 1]
sleep 1;

count
}

count&
N=$!
trap "kill  $N; exit 0;" 2


while true; do
    echo $seconds
    sleep 1;
done


The & makes it run in a subshell, which means that it has its own set of environment variables independent of the current script. Find another way (or another language) to do this.


Ignacio's answer explains that your subshell's environment is not visible to your parent process.

One way to create slaves like this is co-processes (with coproc in zsh and newer bash or with special syntax in ksh). Your bash probably doesn't support this yet.

Here's a variation on your idea that uses signals to send the updates to the parent. I've retained your basic structure where it doesn't conflict:

count() {
    parent=$1
    kill -ALRM $parent
    sleep 1
    count $parent
}

trap 'seconds=$[$seconds + 1]' ALRM

count $$ &
trap "kill $!; exit 0" INT

while true
do
    echo $seconds
done
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜