shellサイクル変数伝達問題

1200 ワード

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