printf在bash中无法正确显示
问题描述:
我的printf语句在终端窗口中显示不正确。 前两个显示正确,但第三个printf "Writing to %s$output%s" "$biwhite" "$color_off"
没有显示,除了最后几个字符$output
printf在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
答
一般来说,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
在特定的位置,你希望这样的替换发生)。
唉唉,我看到了'$ output'时显示的,所以我想我会需要'$ biwhite'和'$ color_off' – Bleakley
当然来bookend它,我想进行着色文件路径 - 但通过为''$ biwhite“,''$ output”'和$“color_off”'中的所有三个放置'%s'占位符,或者只有一个占位符并为其传递完整的连接字符串,您可以如果不将'output'的内容解析为格式字符串本身,也会产生相同的效果。 –
谢谢!非常有帮助! – Bleakley