官术网_书友最值得收藏!

The printf command

The printf command works like echo, except the first argument you provide to it is a format string:

$ printf '%s\n' 'Hello!'
Hello!

Notice that we had to put the format string in single quotes, to prevent the backslash from having special meaning to the shell. Notice also that we didn't have to use double quotes to get the newline from \n; the printf command did that for us.

You can use printf in much the same way you would use a printf() function in other languages, such as C. It supports most of the same format specifications as the printf(1) system command; you can type man 1 printf to see a list.

It's easier to print tricky strings with printf, where echo might struggle:

$ printf '%s\n' -n
-n
$ string=-n
$ printf '%s\n' "$string"
-n

You should always choose printf over echo in scripts, even though it's a little more typing.

Be careful with what you put into a format string; a variable with a value provided by the user can be a security hole! It's best to use only fixed format strings, or carefully build them yourself.

printf also has a useful property where it will repeat the format string as necessary for each argument you provide it. This is a convenient way to print a list of arguments on individual lines:

$ printf '%s\n' foo bar baz
foo
bar
baz

Note that we got three instances of the string-newline pattern from one format string.

Finally, Bash's printf has a %q pattern that can be used to quote special characters in a string with backslashes, so it can be reused safely in the shell. If you follow good quoting practices, you are unlikely to need this a lot in Bash, but it's useful to know it's there:

bash$ printf '%q\n' 'Watch out for thi$ $tring; it \has\ nasty character$!'
Watch\ out\ for\ thi\$\ \$tring\;\ it\ \\has\\\ nasty\ character\$\!
主站蜘蛛池模板: 延安市| 辰溪县| 凤庆县| 石首市| 乌拉特后旗| 明水县| 富川| 常宁市| 莲花县| 绥江县| 辽中县| 辽宁省| 绩溪县| 美姑县| 宁河县| 广丰县| 民丰县| 邓州市| 富顺县| 八宿县| 浦江县| 彭阳县| 寿宁县| 固始县| 龙山县| 开封县| 内江市| 石渠县| 长岭县| 获嘉县| 贞丰县| 米易县| 饶平县| 江达县| 武陟县| 南涧| 包头市| 定襄县| 陈巴尔虎旗| 南澳县| 曲周县|