Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script: use while loop to check string contents using [ ]

I am trying to check a string that is output from a program, if the string matches a certain content, the while-loop will stop the program. At the same time, I need to count how many times the program has run:

x = "Lookup success"  # this is supposed to be the output from the program
INTERVAL=0  # count the number of runs

while ["$x" != "Lookup failed"]   # only break out the while loop when "Lookup failed" happened in the program
do
   echo "not failed"     # do something
   $x = "Lookup failed"     # just for testing the break-out
   INTERVAL=(( $INTERVAL + 10 )); # the interval increments by 10  
done

echo $x
echo $INTERVAL

But this shell script is not working, with this error:

./test.sh: line 9: x: command not found 
./test.sh: line 12: [[: command not found 

Could someone help me please? I appreciate your help.

like image 770
TonyGW Avatar asked Apr 30 '26 10:04

TonyGW


2 Answers

You need spaces around the [ command name. You also need a space before the ] argument at the end of the command.

You also cannot have spaces around assignments in shell. And your assignment in the loop does not need a $ at the start.

x="Lookup success"
INTERVAL=0  # count the number of runs

while [ "$x" != "Lookup failed" ]
do
    echo "not failed"
    x="Lookup failed"
    INTERVAL=(( $INTERVAL + 10 ))  
done

echo $x
echo $INTERVAL
like image 90
Jonathan Leffler Avatar answered May 03 '26 16:05

Jonathan Leffler


Not sure if there's a shell that would accept INTERVAL=((...)); my version of ksh and bash on two platforms does not. INTERVAL=$((...)) does work:

#!/bin/bash

x="Lookup success"
INTERVAL=0  # count the number of runs

while [ "$x" != "Lookup failed" ]
do
    echo "not failed"
    x="Lookup failed"
    INTERVAL=$(( $INTERVAL + 10 ))  
done

echo $x
echo $INTERVAL

Credits go to @JonathanLeffler. I'll appreciate up-votes so that next time I don't have to copy-paste others' solution for pointing out a simple typo (comment rights start with rep>=50).

like image 28
maverick Avatar answered May 03 '26 18:05

maverick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!