Here's part of my script:
#!/bin/sh
n=1
echo "How many repetitions to run (0 = no limit)?"
read reps
if [ $reps = 0 ]; then
while="true"
else
while="[ $n -lt $((reps+1)) ]"
fi
echo "How much off-time in-between reps (in minutes)?"
read time
pwr_init
while $while; do
echo "* Sending power pulse $n"
pwr_normal
t=$time
echo "* Waiting for next power on"
while [ $t -gt 0 ]; do
echo " $t min until next power on"; sleep 60
t=$((t-1))
done
n=$((n+1))
done
Everything is working exactly as I need it to, except for the first while
loop I have going on. Whenever the $while
variable is called, I'd like shell to expand and check the variables at that moment that are defined in the first if
statement.
I can only get shell to expand the variables at the moment of the first if
statement, but then I get the behavior like true
because the comparator is always true and never changes when $n
gets incremented, because that $while
variable has already expanded everything during the first if
statement.
I've tried methods like ${!while}
and various combinations of single and double quotes, but no luck. I usually get errors like $n is a bad number
or bad substitution
.
Right now the only thing I can think of is to add even more if
statements within more functions to check and echo this line to the while
statement every time. I have to believe there's a better way to do this, though, I'm just having a hard time figuring it out (and also finding the right keywords to search for online).
While debugging, I use set -x
, and can see that the comparator string is being evaluated properly in the way the script is written here, but as I mentioned it never updates itself when $n
is incremented.
Does anyone have a trick for this type of substitution that makes life just a little easier? Much appreciated any insight that can be given into this odd variable expansion conundrum!
NOTE1: pwr_init
and pwr_normal
are functions defined elsewhere in the full script.
NOTE2: Take note of the shebang, it must be POSIX compliant. I can't use any fancy bash specific techniques.
EDIT: Getting this to function like I need was less convoluted than I thought, and I'm putting what I added below. However, I'm leaving the question open as it would be great to know whether or not this type of variable expansion can be done.
New script with the check
function wrapped around the if
statement:
#!/bin/sh
n=1
echo "How many repetitions to run (0 = no limit)?"
read reps
count=$((reps+1))
check() {
if [ $reps = 0 ]; then
while="true"
else
while="[ $n -lt $count ]"
fi
}
echo "How much off-time in-between reps (in minutes)?"
read time
pwr_init
while $while; do
echo "* Sending power pulse $n"
pwr_normal
t=$time
echo "* Waiting for next power on"
while [ $t -gt 0 ]; do
echo " $t min until next power on"; sleep 60
t=$((t-1))
done
n=$((n+1))
check
done