linux - 如何使用不同的文件名在不同的 shell 脚本文件中记录 stdout 和 stderr

标签 linux bash shell logging

这是我的脚本文件:-

主.sh

# 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

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"

second_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

first_script.log

Started first_script.sh

second_script.log

Started second_script.sh
Completed second_script.sh
Completed first_script.sh

我想记录的消息应该像下面这样记录在日志文件中。

预期输出:-

主日志

Started main.sh
Completed main.sh

first_script.log

Started first_script.sh
Completed first_script.sh

second_script.log

Started second_script.sh
Completed second_script.sh

我正在从 first_script.sh 调用 second_script.sh 文件。我想将 second_script.sh 使用的日志消息存储在 second_script.log 中

我该怎么做?如果有人不清楚这个问题,请告诉我。

最佳答案

您正在使用 source 以便从 main 脚本中调用脚本。 采购脚本意味着它由当前 shell 本身解析和执行。就好像您在 main 脚本中键入了脚本的内容。即:

当您在 first_script.sh 中调用 second_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进行存储。

为了避免这种情况:

  1. 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"
  1. 或者使用脚本的完整路径从脚本中调用另一个脚本:
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)。以这种方式调用脚本,您需要为您正在调用的脚本添加执行权限。

关于linux - 如何使用不同的文件名在不同的 shell 脚本文件中记录 stdout 和 stderr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46684405/

相关文章:

python - 如何创建 .desktop 文件以在 Linux 上启动 python 脚本?

c - 什么是 "Signal 15 received"

linux - 如何更改几个子目录中多个文件中的一个字符串?

arrays - 匹配 shell 中的单词后分割字符串

json - 使用 jq 从每个主要节点版本获取最新版本

linux - shell 脚本不工作

linux - unix - 文件中的列数

c - 为什么我在设置其他组ID后不调用 "read"?

C++:在 linux shell 脚本中运行 gdb

bash - 在 unix 中,找到并压缩后使用 xargs 移动文件?