2017-03-02 9 views
1

端末ウィンドウに正しく表示されないprintf文があります。 正しく最初の二つの表示が、第三printf "Writing to %s$output%s" "$biwhite" "$color_off"$outputbashでprintfが正しく表示されない

それはある種のバグのように感じているの最後の数文字を除いて表示されません。 printfechoを代入すると、線が正しく表示され、着色が減ります。 私はすべての文を1つに入れようとしました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

Ahhh参照してください... '$ output'は表示されたときに色付けしたいファイルパスですので、' $ biwhite'と '$ color_off'でブックエンドする必要があると思った – Bleakley

+0

確かに - '' $ biwhite ''、' '$ output''、 '' $ color_off "'の3つのプレースホルダーを入れたり、プレースホルダを1つしか持たずに完全な連結文字列を渡すことで、 'output'の内容を書式文字列として解析しなくても、同じ効果が得られます。 –

+0

ありがとう!とても役に立ちました! – Bleakley

関連する問題