3

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#
Braiam
  • 35,380
  • 25
  • 108
  • 167
g4ur4v
  • 1,724
  • 8
  • 27
  • 34

1 Answers1

8

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.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • Hi, the alternative you gave works great but that again doesn't answer why the while loop I am using fails. Adding `-n` to `ssh` don't make any difference here . Thanks for answering. – g4ur4v Nov 27 '12 at 14:19
  • It fails because something in the first pass of the loop is reading from stdin which is that tempo.txt so that the next `read` command has nothing else to read since that has already been read by that command. It's a common problem with ssh in a while loop. `ssh -n` should fix it. If it doesn't, you could also do `ssh < /dev/null` instead or use the suggested alternative. – Stéphane Chazelas Nov 27 '12 at 14:50
  • 1
    Please ignore my comment. `-n` for `ssh` works. – g4ur4v Nov 27 '12 at 15:02