在 bash 脚本中:如何使用 printf 打印包含一些 \n \t 的唯一字符串
in bash script: how to use printf to print a unique string containing some \n \t
我想使用 printf
将 $Usage
打印到 bash 脚本中。
Usage="Usage: \n \
\tjkl [-lbmcdxh] [-f filename]\n \
\t\t[-h] \tThis usage text.\n \
\t\t[-f filename] \t cat the specified file. \n \
\t\t[-l] \tGo to application log directory with ls. \n \
\t\t[-b] \tGo to application bin directory. \n \
\t\t[-c] \tGo to application config directory.\n \
\t\t[-m] \tGo to application log directory and more log file.\n \
\t\t[-d] \tTurn on debug information.\n \
\t\t[-x] \tTurn off debug information.\n"
如何使用 printf
打印它?
我正在考虑使用这个:
printf "%s\n" $Usage
但是没用。
这里的关键点是缺少双引号。一旦你添加它们,你就完成了!这是因为引号启用了扩展。
$ printf "$Usage"
Usage:
\
jkl [-lbmcdxh] [-f filename]
\
[-h] This usage text.
\
[-f filename] cat the specified file.
\
[-l] Go to application log directory with ls.
\
[-b] Go to application bin directory.
\
[-c] Go to application config directory.
\
[-m] Go to application log directory and more log file.
\
[-d] Turn on debug information.
\
[-x] Turn off debug information.
echo
与 -e
一起启用反斜杠转义的解释,因此这也有效:
echo -e "$Usage"
在更简单的情况下查看引用与不引用的区别:
$ printf "hello \nman\n"
hello
man
$
$ printf hello \nman\n
hello$
最后,您可能想好好读一读:Why is printf better than echo?。
您可以使用:
printf "$Usage"
或
printf "%b" "$Usage"
来自 man 1 printf:
%b ARGUMENT as a string with `\' escapes interpreted, except that octal escapes are of the form [=12=] or [=12=]NNN
如果使用 %b
不要忘记在参数周围添加双引号
我想使用 printf
将 $Usage
打印到 bash 脚本中。
Usage="Usage: \n \
\tjkl [-lbmcdxh] [-f filename]\n \
\t\t[-h] \tThis usage text.\n \
\t\t[-f filename] \t cat the specified file. \n \
\t\t[-l] \tGo to application log directory with ls. \n \
\t\t[-b] \tGo to application bin directory. \n \
\t\t[-c] \tGo to application config directory.\n \
\t\t[-m] \tGo to application log directory and more log file.\n \
\t\t[-d] \tTurn on debug information.\n \
\t\t[-x] \tTurn off debug information.\n"
如何使用 printf
打印它?
我正在考虑使用这个:
printf "%s\n" $Usage
但是没用。
这里的关键点是缺少双引号。一旦你添加它们,你就完成了!这是因为引号启用了扩展。
$ printf "$Usage"
Usage:
\
jkl [-lbmcdxh] [-f filename]
\
[-h] This usage text.
\
[-f filename] cat the specified file.
\
[-l] Go to application log directory with ls.
\
[-b] Go to application bin directory.
\
[-c] Go to application config directory.
\
[-m] Go to application log directory and more log file.
\
[-d] Turn on debug information.
\
[-x] Turn off debug information.
echo
与 -e
一起启用反斜杠转义的解释,因此这也有效:
echo -e "$Usage"
在更简单的情况下查看引用与不引用的区别:
$ printf "hello \nman\n"
hello
man
$
$ printf hello \nman\n
hello$
最后,您可能想好好读一读:Why is printf better than echo?。
您可以使用:
printf "$Usage"
或
printf "%b" "$Usage"
来自 man 1 printf:
%b ARGUMENT as a string with `\' escapes interpreted, except that octal escapes are of the form [=12=] or [=12=]NNN
如果使用 %b
不要忘记在参数周围添加双引号