shell 循環中使用管道符的變量問題

 
在shell中,管道里邊改變量是無效的。 
腳本一:
#!/bin/bash
number=0
cat file | while read line;do
    echo $line
   ((number+=1))
   echo "number1=$number"                         //循環內輸出number值
done
echo "number2=$number"                          //循環外取得number值
 
輸出結果
number1=9
number2=0
 
能夠用另外一種方法
腳本二:
#!/bin/bash
number=0
while read line;do
echo $line
((number+=1))
echo "number1=$number"
done < file
echo "number2=$number"
 
輸出結果
number1=9
number2=9
 
此次number賦值在循環外就生效了。
 
腳本練習
#!/bin/bash
cd /home/sum/maillist/sendmail
mailfile=`date +%Y%m%d%H`
export s=0
export f=0
export sum=0
for filename in *
do
  if [ ! -s $filename ]
    then
      echo "delete $filename" >> /home/sum/shell/sendmail.log
      rm -rf $filename
  else
    tmpfile=`cat /home/sum/shell/email_temp.html`
    while read line
     do
        str1=`echo $line |awk -F "#" '{print $2}'`
        str2=`echo $line |awk -F "#" '{print $3}'`
        str3=`echo $line |awk -F "#" '{print $4}'`
        str4=`echo $line |awk -F "#" '{print $5}'`
        mailuser=`echo $line|awk -F "#" '{print $6}'`
        tmp=`echo $tmpfile|sed -e "s/#1#/${str1}/g"`
        tmp=`echo $tmp | sed -e "s/#2#/${str2}/g"`
        tmp=`echo $tmp | sed -e "s/#3#/${str3}/g"`
        tmp=`echo $tmp | sed -e "s/#4#/${str4}/g"`
        echo $mailuser >> /home/sum/shell/sendmail.log
        /usr/local/bin/sendEmail -f xxx@126.com -t "$mailuser" -s maiil.126.com -u "回答您的提問" -xu xxx@126.com -xp 111111 -m "$tmp"  -o message-charset=GB2312 >> /home/sum/shell/sendmail.log
        num=`echo $?`
          if [ $num -eq 0 ];then
            ((s=s+1))
          else
            ((f=f+1))
            echo "mail false user:$mailuser" >> /home/sum/shell/sendmail_false.log
          fi
        ((sum=sum+1))
        sleep 5s
     done < $filename   rm -rf /home/sum/maillist/sendmail/$mailfile  fi done echo "sucess mail:$s" echo "false mail:$f" echo "total send mail:$sum"
相關文章
相關標籤/搜索