Exec 在预置脚本输出时不更新某些 Bash 函数和变量的值

Exec 在预置脚本输出时不更新某些 Bash 函数和变量的值

我在 Bash 中记录消息,在日志消息中添加一些有用的信息以帮助提供上下文。然而,在最终输出中,我的大多数变量和函数似乎只使用它们的初始值,并且每次都不更新。

我尝试将其归结为以下代码:

#!/bin/bash

# Define a timestamp function
function timestamp() {
    date +"%Y-%m-%d %H:%M:%S" # current time
    }

# Define variable
a1="No"
# Function to check variable value
function var_func() {
    echo "${a1}"
    }

# File to record log messages in
log_file="$(pwd)/output.csv" # log file for this script

# Clear log if existing file and send first log msg
echo "Script Initializing" > >(while IFS= read -r line;
            do printf '%s, %s, %s, %s\n' "$(timestamp)" "$(pwd)" "${a1}" "${line}";
            done > "${log_file}")

# Code to execute on future messages
exec >> >(while IFS= read -r line;
            do printf '%s, %s, %s, %s\n' "$(timestamp)" "$(pwd)" "${a1}" "${line}";
            done > >(tee -a -i "${log_file}")) 2>&1

echo "a1=${a1} and dir=$(pwd)" 

a1="Yes"
if [ ! -d "$(pwd)/test" ]; then
    mkdir "$(pwd)/test"
fi
cd "$(pwd)/test"

echo "a1=${a1} and dir=$(pwd)"

我得到的输出是这样的:

2021-06-27 17:38:24, .../Help, No, Script Initializing
2021-06-27 17:38:24, .../Help, No, a1=No and dir=.../Help
2021-06-27 17:38:24, .../Help, No, a1=Yes and dir=.../Help

预期输出是:

2021-06-27 17:38:24, .../Help, No, Script Initializing
2021-06-27 17:38:24, .../Help, No, a1=No and dir=.../Help
2021-06-27 17:38:24, .../Help/test, Yes, a1=Yes and dir=.../Help/test

换句话说,该exec命令似乎只在调用时更新timestamp和的值line。我不明白为什么这些会更新pwd并且a1似乎会重用它们的初始值。

我在这里缺少什么?如果我也可以提供更多有用的详细信息,请告诉我。

谢谢!

真挚地,

实验性

相关内容