我正在使用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。
谢谢 阿萨
答案 0 :(得分:1)
我宁愿这样考虑:
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 ...