
bash printf
Bash provides programming features to make Linux system administrator’s life easier. printf
is one of the most used function used by Linux bash programmers. In this tutorial we will look Linux bash printf
features and use cases while developing bash programs. Bash printf
function is very similar to the C printf function.
Bash提供了编程功能,使Linux系统管理员的工作更加轻松。 printf
是Linux bash程序员最常用的功能之一。 在本教程中,我们将在开发bash程序时查看Linux bash printf
功能和用例。 Bash printf
函数与C printf函数非常相似。
只需打印 (Just Print)
We can use printf
function easily by providing the text in double quotes. In this example we will print Hello Poftut
.
通过在双引号中提供文本,我们可以轻松使用printf
函数。 在此示例中,我们将打印Hello Poftut
。
printf "Hello Poftut"
打印给定文本 (Print Given Text)
We can provide parameters to print text. We will use %s
as text specifier in printf function.
我们可以提供参数来打印文本。 我们将在printf函数中将%s
用作文本说明符。
printf "Hello %s" "Poftut"

打印多个给定文本(Print Multiple Given Text)
We can also provide multiple parameters to the printf command. In this example we will print to the Poftut
, ismail
,ahmet
.
我们还可以为printf命令提供多个参数。 在此示例中,我们将打印到Poftut
, ismail
, ahmet
。
printf "Hello %s " "Poftut" "ismail" "ahmet"
This will print
这将打印

打印整数(Print Integer Numbers)
We can also print integer type values with bash printf function. We will use %d
to print integer values. In this example we will print the age variable.
我们还可以使用bash printf函数打印整数类型值。 我们将使用%d
打印整数值。 在此示例中,我们将打印年龄变量。
printf "My age is %d" 22
This will print
这将打印

打印浮点数(Print Float Numbers)
We can print float type values with bash printf function too. We will use %f
to print float values. In this example we will print the price variable.
我们也可以使用bash printf函数打印浮点类型值。 我们将使用%f
来打印浮点值。 在此示例中,我们将打印价格变量。
printf "Price is %f" 1.99
This will print
这将打印
Price is 1.990000
格式说明符 (Format Specifiers)
We can use format specifiers to print given text or numeric values. We will can specify the floating point decimal part and floating point part with .
. In this example we will print only 2 numbers from floating point parts.
我们可以使用格式说明符来打印给定的文本或数字值。 我们可以使用指定浮点小数部分和浮点部分.
。 在此示例中,我们将仅从浮点部分打印2个数字。
printf "Price is %2.2f" 1.98765
This will print
这将打印

左对齐(Justify Left)
We may need to align the given text to the left. In this situation we will use -
to justify left.
我们可能需要将给定的文本向左对齐。 在这种情况下,我们将使用-
证明左对齐。
printf "% -2.2f" 1.98765
This will print
这将打印
1.99
翻译自: https://www.poftut.com/bash-printf-function-tutorial-examples/
bash printf