Shell – the behavior of while loop and for loop is different

forinputio-redirectionshell

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#

Best Answer

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 "$1@$2" 'stat -fc "scale=2;100*(1-%a/%b)" .' | bc

Which would probably be more robust and future-proof.

Related Question