bash printf literal verbatim string

落花浮王杯 提交于 2019-11-29 15:36:15

Just use -- after printf to let it know that no more arguments are to come and to consider the string as so:

$ printf -- "-dogs-cats" 
-dogs-cats                    # no new line after this

This is a *NIX-trick that can be used for many other commands. As Bash Reference Manual → 4 Shell Builtin Commands says:

Unless otherwise noted, each builtin command documented as accepting options preceded by ‘-’ accepts ‘--’ to signify the end of the options. The :, true, false, and test builtins do not accept options and do not treat ‘--’ specially. The exit, logout, return, break, continue, let, and shift builtins accept and process arguments beginning with ‘-’ without requiring ‘--’. Other builtins that accept arguments but are not specified as accepting options interpret arguments beginning with ‘-’ as invalid options and require ‘--’ to prevent this interpretation.


Note why this happens:

$ printf "-dogs-cats" 
bash: printf: -d: invalid option
printf: usage: printf [-v var] format [arguments]

This makes printf understand the first part of the string, -d, as an argument.

Use a format specification:

printf '%s' "-dogs-cats"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!