Script Shell: Diplay date of two minutes (period)

Hi all,

Here is my script:

  #!/bin/sh 
     while :; 
     do    
        sleep 1    
        date
    done

Please, how can i change this script, i'd like to display the time only of two minutes (period) and exit ? Is that possible ?

Thank you so much for help.
Bests regards.

You'd like your script to run for 2 minutes during which you display date and time each second? One way to solve this is starting a background process that sleeps for 2 minutes and check for its existance:

#!/bin/sh
sleep 120 &
SLEEPER_PID=$!
while ps -p $SLEEPER_PID >/dev/null; do
   sleep 1
   date
done

Edit: on a very busy system there may be a problem that during the 1 second of sleep another process with the same PID as your sleeper was started after the sleeper finished, so use this method with caution. A saver way would be to create a file and delete it after 2 minutes.

#!/bin/sh
F=/tmp/$0.$$
touch $F
( sleep 120 ; rm $F ) &
while [ -f $F ]; do
   sleep 1
   date
done

If i understand that you want:

 i=0;while : ;do sleep 1;i=$((i+1));date;if [ $i == 120 ];then break;fi;done

Why not

i=120; while ((i--)); do sleep 1; date; done
1 Like