Ashley Ashley - 3 months ago 10
Bash Question

Use an extra condition within my while loop in shell script

We do frequent deployments using udeploy and we have there a shell script to restart the apache http server as the last task. Script is simple:-

cd bin_path
sudo ./apachectl -k stop
sleep 5
sudo ./apachectl start
while [ $? -ne 0 ]
do
sudo ./apachectl start
sleep 1
done


Now i would like to include an extra condition in this while loop that checks for a certain value of the counter variable, so that attempt to restart the server is restricted to only say 5 times.
Now here is what i want.

var = 0
sudo ./apachectl start
while [ $? -ne 0 -o $var lte 5 ]
do
var = $((var+1))
sudo ./apachectl start
sleep 1
done


But somehow i'm not an expert in shell script syntax.
If someone can help me correct the script to achieve the desired solution.


Answer

You have several problems.

  1. Shell variable assignments have no spaces around =.
  2. Your while loop is testing the status of sleep, not sudo.
  3. You're using or when you should be using and to combine the conditions.
  4. Comparisons in test need a - prefix.

The correct script should be:

var=0
while ! sudo ./apachectl start && [ $var -le 5 ]
do
    var=$((var+1))
    sleep 1
done
Comments