[转载] 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

猜你喜欢

转载自blog.csdn.net/m0_37962554/article/details/82759218
今日推荐