2017-03-02 111 views
1

我的printf語句在終端窗口中顯示不正確。 前兩個顯示正確,但第三個printf "Writing to %s$output%s" "$biwhite" "$color_off"沒有顯示,除了最後幾個字符$outputprintf在bash中無法正確顯示

感覺就像是某種錯誤。如果我將echo替換爲printf,則行顯示正確,減去着色。 我試過把所有的陳述放在一個printf中,結果相同。這就好像printf真的討厭那一句話。我不知道是什麼原因造成的。我在OSX工作。

biwhite=$(tput bold)$(tput setaf 7) 
#bired=$(tput bold)$(tput setaf 1) 
color_off=$(tput sgr0) 
date="$(date +%Y%m%d)" 


while [[ $# -gt 0 ]] ; do 

input="$1" #name $input as the first arugment sent to script 

if [ -d "$input" ] ; then #if argment is a directory, run md5deep 
    target="${input%/}" #strip the trailing /, if any 
    target="${target##*/}" #drop the leading directory componenets i.e. get basename 
    output="$input"/"$target"_"$date"_checksums.md5 #set .md5 file to $output 
    printf "%s${input##*/}%s is a directory.\n" "$biwhite" "$color_off" 
    printf "Making checksums of all files in %s$input%s\n" "$biwhite" "$color_off" 
    printf "Writing to %s$output%s" "$biwhite" "$color_off" 
    md5deep -bre "$input" >> "$output" #create md5 hash (hashes) of $input and write results to $output 
fi 
shift 

done 

回答

4

一般來說,printf的格式字符串參數應該是常量。因此:

printf '%s%s%s is a directory.\n' "$biwhite" "${input##*/}" "$color_off" # GOOD 
printf 'Writing to %s%s%s\n' "$biwhite" "$output" "$color_off"   # GOOD 

......或者......

printf '%s is a directory.\n' "$biwhite${input##*/}$color_off"   # GOOD 
printf 'Writing to %s\n' "$biwhite$output$color_off"      # GOOD 

至於反對:

printf "%s${input##*/}%s is a directory.\n" "$biwhite" "$color_off"  # BAD 
printf "Writing to %s$output%s\n" "$biwhite" "$color_off"    # BAD 

否則,行爲是很難預測:

  • 任何%"$output"中的符號可能會導致其他位置參數被解釋。
  • 任何反斜槓轉義序列將引用字符取代 - 文字上的標籤爲\t,回車爲\r,等等。(如果你想,使用%b代替%s在特定的位置,你希望這樣的替換髮生)。
+0

唉唉,我看到了'$ output'時顯示的,所以我想我會需要'$ biwhite'和'$ color_off' – Bleakley

+0

當然來bookend它,我想進行着色文件路徑 - 但通過爲''$ biwhite「,''$ output」'和$「color_off」'中的所有三個放置'%s'佔位符,或者只有一個佔位符併爲其傳遞完整的連接字符串,您可以如果不將'output'的內容解析爲格式字符串本身,也會產生相同的效果。 –

+0

謝謝!非常有幫助! – Bleakley