Getting the iteration count in WHILE LOOP


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Getting the iteration count in WHILE LOOP
# 1  
Old 01-06-2015
Getting the iteration count in WHILE LOOP

bash in RHEL 6.4

I have a requirement in which I want to get the iteration count from a WHILE LOOP.

The below mentioned simple script test.sh works fine. In the below script, the WHILE loop will iterate every 5 seconds infinitely until it greps the string BASKETBALL from /tmp/somestring.txt file. Once it greps the string BASKETBALL, it prints the string in the echo command and the loop is terminated using the break command.

Code:
# cat test.sh
export counter=1
while true
do
        if grep -iq BASKETBALL /tmp/somestring.txt
        then
        echo "This loop iterated $counter times before exiting.."
        break
        fi
        sleep 5
        counter=`expr $counter + 1`
done
#
# echo GOLF > /tmp/somestring.txt
# Now, execute the script and it will loop indefinitely as /tmp/somestring.txt file has the string GOLF 
# ./test.sh &
[1] 43208


# #### after few seconds populate /tmp/somestring.txt with the string basketball and the loop will stop iterating

# echo basketball > /tmp/somestring.txt
# This loop iterated 14 times before exiting..

[1]+  Done                    ./test.sh
#

The above script works fine. But, in my real-life script, there is a minor problem. The script itself is executed by root user and then the above portion of the script is executed by another user called appuser after a switch using su command. So, the script will look like below. The double quotes in red mark the beginning and end of commands to be executed by appuser. For this reason, I had to escape the double quotes used in the echo command.

Code:
# cat realLife.sh
sudo su - appuser -c "
export counter=1
while true
do
        if grep -iq BASKETBALL /tmp/somestring.txt
        then
        echo \"This loop iterated \$counter times before exiting..\"
        break
        fi
        sleep 5
        counter=`expr $counter + 1`
done
"
#

Although the WHILE LOOP runs fine with the above script, the echo command is always printing "This loop iterated 1 times before exiting.."
even if the loop iterated multiple times.



Demo:

Code:
# echo POLO > /tmp/somestring.txt
# Now, execute the script as root
# ./realLife.sh &
[1] 53717
# #### after few seconds populate /tmp/somestring.txt with the string basketball and the loop will stop iterating

# echo basketball > /tmp/somestring.txt
# This loop iterated 1 times before exiting..

[1]+  Done                    ./realLife.sh
#

I guess the double qutotes for the su command is confusing the shell. I wish there was some special variable which provides the loop count. Is there a workaround to fix this issue with realLife.sh script?
# 2  
Old 01-06-2015
The second $counter is not escaped.
Better use ' ' instead of " " and do not escape the " " and $var inside the ' '.
Or rerun the whole script in the sudo context:
Code:
if [ "${USER:-$LOGNAME}" = "root" ]
then
  sleep 1 # in case this fails
  exec sudo su - appuser -c "$0 $@"
fi

This User Gave Thanks to MadeInGermany For This Post:
# 3  
Old 01-06-2015
You could also try escaping back quotes..
Code:
counter=\`expr \$counter + 1\`

This User Gave Thanks to ongoto For This Post:
# 4  
Old 01-06-2015
Hi MadeinGermany
I cannot use single quotes as there are several SQLs using string literals with single quotes within the su -c block that can cause the shell to get confused.

For eg:
select to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual;

Thank you for pointing out the missing escape character for the second $counter variable

ongoto's suggestion of escaping the backtick seems to fix this issue. The following script has worked. SmilieSmilie

I need to check if it works in my real life script. THANK YOU BOTH VERY MUCH.


Code:
# cat realLife.sh
sudo su - appuser -c "
export counter=1
while true
do
        if grep -iq BASKETBALL /tmp/somestring.txt
        then
        echo This loop iterated \$counter times before exiting..
        break
        fi
        sleep 5
        counter=\`expr \$counter + 1\`
done
"

# 5  
Old 01-06-2015
Hello John K,

How about counter++ in that, if this works then no need to mess with escaping the quotes.

Thanks,
R. Singh
This User Gave Thanks to RavinderSingh13 For This Post:
# 6  
Old 01-06-2015
Hi Ravinder
Can you provided some more details on this so that I can google on this.
Any man page available for this ?
# 7  
Old 01-06-2015
Sorry John K I was thinking to do increment the variable but it doesn't work in that way, I think ongoto, MadeInGermany has given good solution for same.


Thanks,
R. Singh
This User Gave Thanks to RavinderSingh13 For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

While loop is running only for the first iteration

Hello, I've written a script to automate encoding of all the MP4 files in a directory (incl. subdirectories). But unfortunately it's running for the first MP4 file only. My machine details: root@Ubuntu16:~# uname -a Linux Ubuntu16 4.10.0-28-generic #32~16.04.2-Ubuntu SMP Thu Jul 20 10:19:48... (2 Replies)
Discussion started by: prvnrk
2 Replies

2. Shell Programming and Scripting

Loop iteration with two variables

Hello, I have been stuck on this for some time and invested many hours trying to find a solution. I am trying to either loop through two variables or or two arrays and not sure how to do it. I am limited to ksh only, and don't have the ability to do a foreach, or for i AND for j etc...I... (19 Replies)
Discussion started by: Decoy Octopus88
19 Replies

3. Shell Programming and Scripting

While loop is causing ssh command to exit from script after first iteration.

I am trying to check multiple server's "uptime" in a loop over "ssh". When I execute multiple ssh commands with hard coded servernames script is executing fine. But when I pass server names using while loop, script is exiting after checking first server's status, why? # serverList... (8 Replies)
Discussion started by: kchinnam
8 Replies

4. Shell Programming and Scripting

Do something only that last iteration of loop

I have a script with logic like: my_function() { if mkdir $1 mkdir mydir_${2} else do something else fi } read in list of items while read list do my_function $list `date` done so basically it will make a directory for every name in the list and create a directory with the... (6 Replies)
Discussion started by: glev2005
6 Replies

5. Shell Programming and Scripting

For Loop in shellscript - Printing Output for every iteration

for VGLIST in `lsvg -o` do CLOSED_OUT=`echo $VGLIST | lsvg -l $VGLIST | awk '{print $6 " " $7}' | grep closed` if ]; then echo "Filesystems $CLOSED_OUT in VG that are in Closed status" else echo "\n Some message" fi Above Code is working fine, but echo "Filesystems $CLOSED_OUT... (8 Replies)
Discussion started by: chandu123
8 Replies

6. Shell Programming and Scripting

while loop stops after first iteration - remote ssh exit command problem?

I have written the following script to update some Debian boxes. #!/bin/bash mxg_hosts_file="/etc/mxg/ssh-hosts" while read line ; do mxg_host="$(echo ${line} | awk -F":" '{print $1}')" mxg_port="$(echo ${line} | awk -F":" '{print $2}')" echo "Connecting and Upgrading... (3 Replies)
Discussion started by: jelloir
3 Replies

7. Shell Programming and Scripting

for loop iteration and shell programming startup

question :how can i iterate to next item in for loop with the loop e.g for i in `cat abc.txt` do echo $i // this will display first line i=$i+1; // this doesnt work for me. echo $i; //this will display secound line done question: is my approach to manipulate text good? I have... (3 Replies)
Discussion started by: kashif_islam
3 Replies

8. Shell Programming and Scripting

howto stop loop iteration

I wonder how to stop further loop iterations when conditions gets false e.g. This file.txt contains the following structure : 1 2 3 4 5 6 7 8 9 10 How to stop iteration when if statement gets false ? for n in `cat file.txt` do if (( n<=5 )) (1 Reply)
Discussion started by: presul
1 Replies

9. Shell Programming and Scripting

Pick up the return code for every iteration and display the result only once in loop.

Hi All, I amlearning UNIX scripting. I have a small query. I would be thankful if any one helps me out. I have a below piece of code which delets the files. If file dosent have the permissions to delete a particular file I have used 2>>operator to track the error code. But my objective is... (1 Reply)
Discussion started by: manas6
1 Replies

10. Shell Programming and Scripting

New iteration of for-loop without incrementing?

Another question, is it possible to, in a for-loop incrementing until it reaches a certain number, to have it loop again without incrementing? Just have it drop what it is doing when it reaches this command and start again at the same number it was at? I know I could make a while loop and just... (0 Replies)
Discussion started by: jeriryan87
0 Replies
Login or Register to Ask a Question