Matt
Matt

Reputation: 2896

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

Upvotes: 1

Views: 90

Answers (2)

Ben Jackson
Ben Jackson

Reputation: 93720

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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798666

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.

Upvotes: 2

Related Questions