Problems with shell-script while!
First of all, I'm a beginner on shell-script. This code I've done is not working.
I want to repeat a code for 30 seconds but it doesn't work. It just keep doing my logic indefinitely.
DIFF=0
while [ $DIFF < 30 ]; do
START=$(date +%s)
######## My logic #开发者_如何学运维########
DIFF=$(( $END - $START ))
echo $DIFF
cd ..
sleep 5s
done
I think it's because I'm not doing the while clause properly?
Well, you definitely need to provide some values for $START
and $END
. They won't set themselves!
You may want to do something like
START = `date +%s`
to set it to a time in seconds. Of course END
will need to be set inside your loop to get it updated.
EDIT: cd ..
is hopefully not really what you plan to run inside the loop. Within a few milliseconds your current directory will be the root directory, with little else accomplished. It would be cheaper to do a single cd /
.
EDIT 2: This shouldn't be such a hard problem. For this edit, I've built and tested a one-line solution:
START=$(date +%s); DIFF=0; while [ $DIFF -lt 30 ]; do echo $DIFF; DIFF=$(($(date +%s)-$START)); done
That will correctly update its variables and display them... and it ends after 30 seconds.
((end = $(date +%s) + 30))
while (( $(date +%s) < end ))
do
something
done
Or, using the builtin variable $SECONDS
in Bash:
((end = SECONDS + 30))
while (( SECONDS < end ))
do
something
done
use an infinite loop. an example pseudocode
DIFF=0
while true
do
START=$(date +%s)
END=.... #define your end
DIFF=$((END-START))
if [ "$DIFF" -gt 30 ] ;then
break
fi
.....
done
It looks like you're using bash.
Try something like this perhaps:
START=...
while (($DIFF<30)); do
# ....
DIFF=$((END-START))
done
(See Bash arithmetic evaluation and The Double-Parentheses Construct.)
精彩评论