while 루프와 for 루프가 다르게 동작하는 이유는 무엇입니까?

while 루프와 for 루프가 다르게 동작하는 이유는 무엇입니까?

파일에서 사용자 및 서버 세부 정보를 읽은 tempo.txt다음 다른 스크립트를 사용하여 해당 unix 계정에서 파일 시스템의 디스크 공간 사용량을 확인하려고 합니다 server_disk_space.sh. 하지만 왜 while 루프는 첫 번째 행에서만 작동하고 for 루프는 잘 작동하는지 알 수 없습니다. 이것을 이해하도록 도와주세요.

while 루프 사용

#!/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

산출

8

for 루프 사용

#!/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

산출

8
23
54
89
12

콘텐츠server_disk_space.sh

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

Use percentage위 스크립트는 모든 서버의 디스크 사용량 값을 출력합니다.


콘텐츠tempo.txt

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

답변1

-n옵션을 추가 하지 않는 한 ssh표준 ssh입력에서 읽혀집니다. while 루프의 경우 tempo.txt 파일입니다.

또는 다른 파일 설명자를 사용하여 tempo.txt 파일을 읽을 수 있습니다.

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

이러한 서버가 GNU/Linux 서버인 경우 SSH 스크립트는 다음과 같을 수 있습니다.

#! /bin/sh -
ssh -n "$1@$2" 'stat -fc "scale=2;100*(1-%a/%b)" .' | bc

이는 더욱 강력하고 미래 지향적일 수 있습니다.

관련 정보