2015-03-13 133 views
0

在我的shell腳本中,我定義了幾條需要記錄爲INFO,WARN或ERROR的消息。字符串bash中的參數替換

的消息如下:

###### This may not be correct syntax as I need to know this ####### 
BACKUP_INFO="File {} is compressed at path {}." 
ERROR_FILE_NOT_EXIST="File {} doesn\'t exist." 
OTHER_ERROR="Cannot backup File {}, Reason: {}" 

我有一個方法來記錄在文件中這樣的信息:

function print_info() { 
    echo -e "$(date +'%F %T') ${SCRIPTNAME}: INFO: ${*}" | tee -a ${LOGFILE}; 
} 

現在我需要通過我的消息的方法打印信息在這樣一個第一個參數應放在第一個{}處,第二個參數放置在第二個{}處,等等。

即使我想聲明我的消息

BACKUP_INFO="File $FILE_NAME is compressed at path $BACKUP_DIR." 

但問題是變量FILE_NAME和BACKUP_DIR是在方法內部,消息是全局定義。

有點我想用它,如下圖所示:

print_info $BACKUP_INFO $FILE_NAME $FILE_PATH 

使輸出應是

2015-03-13 07:05:05 : INFO: File /opt/mgtservices/relay.log is compressed at path /root/backup 

我需要知道正確的語法,我怎麼能做到這一點。

回答

1

對此,您可以使用printf,使用「%s」作爲佔位符。

下面是一個例子:

SCRIPT_NAME="foo.sh" 
FORMAT="hello %s, %s" 

print_info() { 
    format="$1" 
    shift 
    printf "$(date +%F) $SCRIPT_NAME: $format\n" "[email protected]" 
} 

name="bob" 
message="how are you?" 

print_info "$FORMAT" "$name" "$message" 
1

由於參數是上下文相關的,無論如何,它並沒有真正多大意義,這些抽象到您在全局變量的消息字符串的地步。無論哪種功能需要打印BACKUP_INFO也需要知道字符串中的佔位符,因此它可能直接包含字符串。如果你不想這樣做,也許可以把它們變成功能。

print_info() { 
    local fmt 
    fmt=$1 
    shift 
    printf "$(date +'%F %T') ${SCRIPTNAME}: INFO: $fmt\n" "[email protected]" | tee -a "$LOGFILE" 
} 

backup_info() { print_info 'File %s is compressed at path %s.' "$1" "$2"; } 
error_file_not_exist() { print_info "File %s doesn't exist." "$1"; } 
# XXX FIXME: "other_error" is really a misnomer! 
other_error() { print_info 'Cannot backup File %s, Reason: %s' "$1" "$2"; } 

有點巧合的是,這實際上也是,如果你想爲你的腳本的本地化支持提供一些好處;那麼如果英文字符串的單詞順序對於目標語言是錯誤的,翻譯器可以用不同的英文格式功能覆蓋。