shell 循环变量传递问题

来源:互联网 发布:华为手机root软件 编辑:程序博客网 时间:2024/05/22 01:46

如例子中:

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


执行结果如下(后面一部分)

hello,hplip your UID is 11332hello,saned your UID is 11433hello,lsn your UID is 100034hello,sshd your UID is 11535number is 0


为什么变量num没有被传递?

定义为环境变量没有用的,环境变量只是在子进程创建的时候可以从父进程复制到子进程,它无法实现从子进程往父进程传递,也不能在子进程运行期间从父进程获得新值。

解决办法是不要产生子进程


如下:

#!/bin/bashfile="/etc/passwd"let num=0while read linedo        echo -e "hello,`echo $line|cut -d ":" -f 1` \c"        echo your UID is `echo $line|cut -d ":" -f 3`        num=$[$num+1]        echo $numdone < $fileecho number is $num


执行结果:

hello,speech-dispatcher your UID is 11231hello,hplip your UID is 11332hello,saned your UID is 11433hello,lsn your UID is 100034hello,sshd your UID is 11535number is 35



1 0