导出后无法在函数外部使用局部变量

导出后无法在函数外部使用局部变量

这是我的剧本。即使使用导出命令后也无法使用块之外的变量。下面是我尝试过的代码。我尝试过其他选项,例如,declare -x var但这也不起作用。有人可以对此发表评论吗,我做得对吗?

#!/bin/bash
{
    var="123"  
    export var   # exporting the variable so that i can access from anywhere   
    echo "var is "$var     # able to get the value of this variable
} | tee   log.txt

echo "var is "$var   # not able to get the value of this variable

答案1

根据接受的 SOF 答案:

在管道中,所有命令在不同的进程中同时运行(其标准输出/标准输入通过管道连接)。

因此,尽管大括号本身不会创建子 shell,但管道会执行此操作(在 bash 中);参见例如

#!/bin/bash
var=256

ps -u | grep $0
{
ps -u | grep $0
{
var="123"  
export var
echo "var is "$var

ps -u | grep $0

} | tee log.txt
echo "var is "$var
}

echo "var is "$var

所以我们想要的是避免使用管道,同时仍然在屏幕上和日志文件中输出。幸运的是 bash 具有<(...)创建临时 FIFO 的功能。下面的示例显示了一种可能性,即人们仍然可以使用代码块,将其整个输出传输到日志(此处stdout并附stderr加到不同的日志文件),并在以后访问更改的变量,因为我们没有进入子 shell。

#!/bin/bash

VAR=123
echo "VAR first: $VAR"

{
        VAR=256
        echo "VAR in block: $VAR"
        norealcommand
        # show open files to see FIFOs
        #lsof -p $$
        date
        otherbadcommand
}> >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)

# dummy output to not mess up output order
echo | cat 

#lsof -p $$
echo "VAR after block: $VAR"

cat -n stdout.log 
cat -n stderr.log

这应该会导致这样的结果:

$ ./fifo                                                                            /dev/shm |myself@mydesk|0|12:04:10 
VAR first: 123
VAR in block: 256
./fifo: line 9: norealcommand: command not found
Mon Jul  3 12:04:37 CEST 2017
./fifo: line 13: otherbadcommand: command not found

VAR after block: 256
     1  VAR in block: 256
     2  Mon Jul  3 12:04:10 CEST 2017
     3  VAR in block: 256
     4  Mon Jul  3 12:04:37 CEST 2017
     1  ./fifo: line 9: norealcommand: command not found
     2  ./fifo: line 13: otherbadcommand: command not found
     3  ./fifo: line 9: norealcommand: command not found
     4  ./fifo: line 13: otherbadcommand: command not found

希望这能让你开心:-)

相关内容