I have a function that opens a file descriptor to fd 3 which redirects to a file. The issue I have is that STDOUT from other functions is getting written to the file that fd3 is writing to. So the code is something like below.
I don't understand how opening file descriptor 3 at start_report function allows output from log or any other function that writes to STDOUT to be written to /tmp/testfile.log. The odd thing is that not all STDOUT is getting written to fd 3, only some.
start_report () {
exec 3>/tmp/testfile.log
cat <<EOF >&3
Some text is written to a report.
EOF
}
report_update () {
cat <<EOF >&3
some more text is written to a report.
EOF
}
end_report () {
cat <<EOF >&3
some ending text is written to a report.
EOF
exec 3>&-
}
log () {
#$1 = function name
#$2 = log message
echo "$1" "$2"
}
main () {
start_report
log "${FUNCNAME[0]}" "Starting main"
update_report
log "${FUNCNAME[0]}" "updating report"
end_report
}
main
The statement
opens
/tmp/testfile.log
on file descriptor 3 in the shell that executes the statement. Even though it occurs inside a function, it affects the shell that executes the function; i.e., it is not scoped to the body of the function. Oncestart_report
is executed by the current shell, file descriptor 3 remains attached to/tmp/testfile.log
until it is closed or reassigned.log
, however, doesn't write to file descriptor 3; it only writes to standard output (file descriptor 1). The other functions redirect the standard output of their commands to file descriptor 3.