shell 循环变量传递问题

本文探讨了Bash脚本中变量传递的问题,通过两个示例对比解释了如何避免因子进程导致的变量传递失败,并给出了正确的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如例子中:

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值