Why the behavior of while loop and for loop is different?

I am trying to read user and server details from file tempo.txt and then check the disk space usage of the file system on that unix account using another script server_disk_space.sh.But I am not able to figure out why while loop is only working for first line and for loop is working fine.Please help me understand this.

Using while loop

#!/usr/bin/ksh
while read line
do
r1=`echo $line | cut -d"#" -f1`;
r2=`echo $line | cut -d"#" -f2`;
apx_server_disk_space.sh $r2 $r1
done<tempo.txt

Output

8

Using for loop

#!/usr/bin/ksh
for line in $(cat tempo.txt)
do
r1=`echo $line | cut -d"#" -f1`;
r2=`echo $line | cut -d"#" -f2`;
apx_server_disk_space.sh $r2 $r1
done

Output

8
23
54
89
12

Contents of server_disk_space.sh

#!/usr/bin/ksh
user=$1
server=$2
count=`ssh ${user}@${server} "df -h ."`
echo ${count} | awk '{print $12}' | tr -d %

Above script outputs the value of Use percentage of Disk Usage on any server .


Contents of tempo.txt

abclin542#abcwrk47#
abclin540#abcwrk1#
abclin541#abcwrk2#
abclin543#abcwrk3#
abclin544#abcwrk33#

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Unless you add the -n option to ssh, ssh will read from its standard input, which in the case of the while loop is the tempo.txt file.

Alternatively, you can use a different file descriptor to read the tempo.txt file:

#! /usr/bin/ksh -
while IFS='#' read <&3 -r r1 r2 rest; do
  apx_server_disk_space.sh "$r2" "$r1"
done 3< tempo.txt

If those servers are GNU/Linux servers, your ssh script could be:

#! /bin/sh -
ssh -n "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eecadfae">[email protected]</a>$2" 'stat -fc "scale=2;100*(1-%a/%b)" .' | bc

Which would probably be more robust and future-proof.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x