以下是我的脚本文件: -
# Log stdout and stderr
log_stdout_and_stderr() {
# Close STDOUT file descriptor
exec 1<&-
# Close STDERR FD
exec 2<&-
# Open STDOUT as $1 file for read and write.
exec 1<>$1
# Redirect STDERR to STDOUT
exec 2>&1
}
Log a single line
log() {
echo "[$(date)]: $*"
}
log_stdout_and_stderr main.log
log "Started main.sh"
log "Completed main.sh"
# call first_script
source first_script.sh
log_stdout_and_stderr first_script.log
log "Started first_script.sh"
# call second_script
source second_script.sh
log "Completed first_script.sh"
log_stdout_and_stderr second_script.log
log "Started second_script.sh"
log "Completed second_script.sh"
以下是我的输出日志: -
Started main.sh
Completed main.sh
Started first_script.sh
Started second_script.sh
Completed second_script.sh
Completed first_script.sh
我想在日志文件中记录日志消息,如下所示。
预期产出: -
Started main.sh
Completed main.sh
Started first_script.sh
Completed first_script.sh
Started second_script.sh
Completed second_script.sh
我从first_script.sh调用second_script.sh文件。我想在second_script.log
中存储second_script.sh使用的日志消息我该怎么办?如果有人不清楚这个问题,请告诉我。
答案 0 :(得分:1)
您正在使用source
来调用main
脚本中的脚本。
获取脚本意味着它由当前shell本身解析和执行。就像您在main
脚本中键入脚本的内容一样。即:
以下内容相当于您在second_script.sh
中调用first_script.sh
:
<强> first_script.sh 强>
log_stdout_and_stderr first_script.log
log "Started first_script.sh"
# call second_script
####### second_script.sh called with sourcing #######
log_stdout_and_stderr second_script.log
log "Started second_script.sh"
log "Completed second_script.sh"
######################################################
log "Completed first_script.sh"
由于脚本将按顺序执行,因此将根据上次调用的log_stdout_and_stderr
存储日志。
为了避免这种情况:
first_script.sh
修改为:log_stdout_and_stderr first_script.log log "Started first_script.sh" #call second_script source second_script.sh log_stdout_and_stderr first_script.log log "Completed first_script.sh"
log_stdout_and_stderr first_script.log log "Started first_script.sh" # call second_script /path/to/second_script.sh log "Completed first_script.sh"
这样你就可以调用另一个bash shell来执行另一个脚本(在本例中为second_script.sh
)。以这种方式调用脚本,您需要为正在调用的脚本添加执行权限。