Time Counter in a Shell Script
I want to execute a command at every 2 seconds and another command at every 5 secs in a while loop.
start
while [ 1 ]
do
if [ time diff == 2]
do sth
fi
if [ time diff == 5]
do sth else
fi
end
dif = end - start
But this is a little problem when difference is 0. How can i do similar to this in 开发者_开发技巧a shell script?
Try this:
while true; do sth ; sleep 2 ; done
You can use a subshell:
#!/bin/bash
(while true ; do echo time2 ; sleep 2 ; done)&
(while true ; do echo time5 ; sleep 5 ; done)
However, you will have to do something to kill the background subshell later.
try sleep
while true
do
..
sleep 2
done
possibly the simplest approach is a 10 second loop like this! (since 10 is the lowest common denominator of 2 and 5)
while true
do
sth
sleep 2
sth
sleep 1
sth else
sleep 1
sth
sleep 2
sth
sleep 2
sth
sth else
sleep 2
done
It's a bit crazy though!
Of course this assume the commands are instant, you may want to background them with &
If you wanted to be very very thorough, you could use this as a starting point
#!/bin/bash
declare -a JOBPIDS
function repeatbackground()
{
local delay="$1"
shift
(
while true
do
sleep "$delay" || return 0 # abort on sleep interrupted
eval "$@"
done
)&
JOBPIDS=( ${JOBPIDS[@]-} $! )
}
function signalbackgroundtasks()
{
for bgpid in "${JOBPIDS[@]}"
do
kill -TERM "$bgpid" || echo "Job $bgpid already vanished"
done
JOBPIDS=( )
}
trap "signalbackgroundtasks; exit 0" EXIT
repeatbackground 2 echo "by the other way"
repeatbackground 5 echo the other background job
echo "Running background jobs ${JOBPIDS[@]}"
wait
exit 0
#!/bin/bash
#
rhythm () {
beat1=$1
beat2=$2
tick=0
while [ 1 ]
do
(( tick % $beat1)) || echo a
(( tick % $beat2)) || echo b
tick=$(((tick+1)%(beat1*beat2)))
sleep 1
done
}
rhythm 2 5
This works, of course, only for 2 parameters, and if the the time consumed by echo in the example/ the real command in real, is insignificant.
The following doesn't use bash-specific features or subshells and is easy to generalize:
set 1 2 3 4 5
while :; do
sleep 1
shift
case $1 in
2|4) echo "every 2 seconds" ;;
5) echo "every 5 seconds" ; set 1 2 3 4 5 ;;
esac
done
精彩评论