如何在不停止脚本的情况下终止 shell 脚本中的日志记录进程?

How to terminate the logging process inside a shell script withput stopping the script?

我正在使用 shell 脚本来 运行 我的分析。为了确保,我可以确认执行了正确的命令,我正在将完整的 STDOUT/STDERR 输出写入文件

我的脚本是这样的:

#!/bin/bash

# Here are some pliminary stuff

echo " this goes still to the STDOUT to control the begining of the script"

#### execute all output to log files
# to set a log file, where all echo command will be redirected into.
touch $projectName\_logfile.txt # creating the log file
exec &> $projectName\_logfile.txt # direct all output to the log file

echo "1. These steps should be written to the log file"

# exit 
# exec >&-

echo "2. 2. these steps should be written to the STDOUT again!"

# The script should be able to continue here ...

如您所见,我已经尝试使用 exit 命令以及再次使用 exec 关闭文件描述符。但两者都失败了。

非常感谢您帮助我了解如何关闭与日志文件的连接并将所有内容重定向回 STDOUT/STDERR。

谢谢 阿萨

我宁愿这样考虑:

echo "to out 1"
{
  echo "to log 1"
  echo "to log 2"
} &> ./_logfile.txt 
echo "to out 2"

无论如何,如果您仍然需要使用您的方法,那么您需要保存原始文件描述符:

exec 3<&1 # save original stdout to 3
exec 4<&2 # save original stderr to 4

然后恢复:

exec 1>&3 # restore original stdout
exec 2>&4 # restore original stderr

你的例子:

#!/bin/env bash

echo " this goes still to the STDOUT to control the begining of the script"

touch ./_logfile.txt # touch the log file
exec 3<&1 # save original stdout to 3
exec 4<&2 # save original stderr to 4
exec &> ./_logfile.txt # direct all out and err to the log file

echo "1. These steps should be written to the log file"

exec 1>&3 # restore original stdout
exec 2>&4 # restore original stderr

echo "2. 2. these steps should be written to the STDOUT again!"

# The script should be able to continue here ...