1. 程式人生 > >[轉載] shell 迴圈變數傳遞問題

[轉載] shell 迴圈變數傳遞問題

shell 迴圈變數傳遞問題

2016年04月07日 17:00:04 光頭阿瓜 閱讀數:3241更多

個人分類: linux

如例子中:

 

#!/bin/bash

file="/etc/passwd"
let num=0
cat $file | while read line
do
        echo -e "hello,`echo $line|cut -d ":" -f 1` \c"
        echo your UID is `echo $line|cut -d ":" -f 3`
        num=$[$num+1]
        echo $num
done
echo number is $num

 

 

執行結果如下(後面一部分)

 

hello,hplip your UID is 113
32
hello,saned your UID is 114
33
hello,lsn your UID is 1000
34
hello,sshd your UID is 115
35
number is 0

 

 

為什麼變數num沒有被傳遞?

定義為環境變數沒有用的,環境變數只是在子程序建立的時候可以從父程序複製到子程序,它無法實現從子程序往父程序傳遞,也不能在子程序執行期間從父程序獲得新值。

解決辦法是不要產生子程序

 

如下:

 

#!/bin/bash

file="/etc/passwd"
let num=0
while read line
do
        echo -e "hello,`echo $line|cut -d ":" -f 1` \c"
        echo your UID is `echo $line|cut -d ":" -f 3`
        num=$[$num+1]
        echo $num
done < $file
echo number is $num

 

 

執行結果:

 

hello,speech-dispatcher your UID is 112
31
hello,hplip your UID is 113
32
hello,saned your UID is 114
33
hello,lsn your UID is 1000
34
hello,sshd your UID is 115
35
number is 35