【Shell】while 循环中的变量无法保存|无法获取while中的变量|管道中的函数变量无法获取问题

例子:

[liuhao@slave04 ~]$ cat test.sh 
#! /bin/sh
 
x=1
echo "adasd" | while read line
do
    x=2 
done
echo $x
 
运行结果是
[liuhao@slave04 ~]$ sh test.sh 
1

原因
 
原来是因为管道|创建了新的子进程,而子进程是在独立的进程空间(Context)运行了. 需要跟父进程通信的话, 得使用进程间通信机制. 不是简单的变量问题。
 

解决办法: 

1、命名管道

shell中引用while中的变量 - Shell-Chinaunix


mkfifo pipe;
exec 3<>pipe;  #fd3 指向pipe

echo "a b c" |while read line1 line2
do
echo $line1 >&3 # 写入fd3
done

read -u3 var #读取变量
echo $var
rm pipe;
exec 3>&-

2、改为管道输入为文件输入

shell while内获取外部变量内容 - 李秋 - 博客园

#!/bin/sh
x="this is the initial value of x"
while read line;do
        x="$line"
        echo $x
done < /tmp/tmp
echo x = $x

3、输入重定向

shell while内获取外部变量内容 - 李秋 - 博客园

#!/bin/sh
x="this is the initial value of x"
exec 3<&0         # save stdin 将标准输入重定向到文件描述符3
exec < /tmp/tmp # 输入文件
while read line; do
        x=$line
        echo $x
done
exec 0<&3        # restore stdin
echo x = $x

4、临时文件桥接

MY_UUID=$(uuidgen)#或者$(cat /proc/sys/kernel/random/uuid)
MY_TMP_FILE_PATH=/tmp/${MY_UUID}.txt

x="this is the initial value of x"

while read line
do

x=$line
echo $x

done < ${MY_TMP_FILE_PATH}

echo $x

posted on 2022-10-04 01:22  bdy  阅读(46)  评论(0编辑  收藏  举报

导航