2017-10-11 82 views
2

這裏是我的腳本文件: -如何使用不同的文件名進行登錄輸出和錯誤在不同的shell腳本文件

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

first_script.log

Started first_script.sh 

second_script.log

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

我想日誌消息應記錄如下面的日誌文件。

預期輸出: -

main.log

first_script.log

Started first_script.sh 
Completed first_script.sh 

second_script.log

Started second_script.sh 
Completed second_script.sh 

我打電話second_script.sh文件從first_script.s H。我想在second_script.log中存儲second_script.sh使用的日誌消息

我該怎麼辦?如果有人不清楚這個問題,請告訴我。

+0

只需在該行'source second_script.sh'後面的'first_script.sh'中添加'log_stdout_and_stderr first_script.log'行即可。 – Ardit

回答

1

您正在使用source來調用main腳本中的腳本。 源腳本意味着它由當前shell本身解析和執行。就好像您在main腳本中輸入了腳本的內容。即:

下面是一個等效當調用second_script.shfirst_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" 
  • 或撥打另一個腳本從內腳本使用腳本的完整路徑:
  • 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)其他腳本。以這種方式調用腳本,您需要爲您調用的腳本添加執行權限。

    +0

    我已經在使用你的第一種方法了。因爲我在main.sh中使用了應該在所有腳本中使用的變量。所以我使用「source first_script.sh」從first_script.sh中的main.sh中獲取值。 – karan

    +0

    你嘗試過兩種選擇嗎? – Ardit

    +0

    我目前正在使用第一個選項。我還沒有嘗試過第二種選擇。第二個選項是否可以從主腳本獲取變量而不需要傳遞它們? – karan

    相關問題