您的位置:首页 > 运维架构 > Shell

shell 循环变量传递问题

2016-04-07 17:00 351 查看
如例子中:

#!/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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: