我的printf语句在终端窗口中无法正确显示。
前两个显示正确但第三个printf "Writing to %s$output%s" "$biwhite" "$color_off"
未显示,除了$output
的最后几个字符
感觉就像某种错误。如果我将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
答案 0 :(得分: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
。