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

时间:2017-10-11 09:17:36

标签: linux bash shell logging

以下是我的脚本文件: -

main.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"

以下是我的输出日志: -

main.log

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

我想在日志文件中记录日志消息,如下所示。

预期产出: -

main.log

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.log

中存储second_script.sh使用的日志消息

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

1 个答案:

答案 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存储日志。

为了避免这种情况:

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