0

I am logging messages in Bash where I add some useful information to the log message to help provide context. However, in the final output most of my variables and functions appear to only use their initial values and do no update each time.

I've tried to boil this down into the following code:

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

The output I get is this:

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

The expected output is:

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

In other words, the exec command appears to only update the values of timestamp and line when called. I don't understand why these will update yet pwd and a1 appear to reuse their initial values.

What am I missing here? Let me know if I can provide more helpful details too.

Thanks!

Sincerely,

Exper1mental

  • 1
    Relevant: [Is the command in a process substitution invoked in a subshell?](https://unix.stackexchange.com/q/331176/108618) – Kamil Maciorowski Jun 27 '21 at 22:14
  • Indeed, that definitely appears to be the cause of the issue. For the `echo` command there appears to be a simple fix: `echo "Script Initializing" | format_output > "${log_file}"` with `function format_output() { declare i=${1:-$( – Exper1mental Jun 28 '21 at 11:44
  • However, for the `exec` command, it appears I need to familiarize myself more with proper Bash syntax and perhaps devise a more creative solution. `exec >> format_output >> >(tee -a -i "${log_file}") #2>&1` isn't working. – Exper1mental Jun 28 '21 at 12:40

0 Answers0