“printf”格式:“Space”和“%-s \ n”

“printf”格式:“Space”和“%-s \ n”

我正在学习 shell 脚本。有些教程中有一行样例代码我看不懂。有人能告诉我下面代码中第一行的含义吗?

format="%8s%10s%10s   %-s\n"
printf "$format" "Dirs" "Files" "Blocks" "Directory"

total_dirs=$(find $HOME -type d | wc -l)
total_files=$(find $HOME -type f | wc -l)
total_blocks=$(du -s $HOME)

printf "$format" $total_dirs $total_files $total_blocks

我的问题是关于第一行的后半部分。

  1. 关于“space”的用法:

如果 $3 和 $4 之间有 3 个空格,那么输出的行 $3 和 $4 之间是否也有 3 个空格?

  1. 关于“%-s \ n”部分:

此示例代码中的“-(连字符)”是什么意思?即使我删除了它,我得到的输出结果仍然相同。

答案1

bash shell 内置命令从相应的C例程中继承了它的格式说明符,因此通常最有用的参考是man 3 printf。从那里:

  1. 是的,任何不属于格式说明符的字符都会按字面意思打印
   Format of the format string
       The format string is a character string, beginning and  ending  in  its
       initial  shift state, if any.  The format string is composed of zero or
       more  directives:  ordinary  characters  (not  %),  which  are   copied
       unchanged  to the output stream; and conversion specifications, each of
       which results in fetching zero or more subsequent arguments.  Each con‐
       version specification is introduced by the character %, and ends with a
       conversion specifier.  In between there may be (in this order) zero  or
       more  flags, an optional minimum field width, an optional precision and
       an optional length modifier.
  1. 它指定该值应该左对齐
   -      The converted value is to be left adjusted on the  field  bound‐
          ary.  (The default is right justification.)  The converted value
          is padded on the right with blanks, rather than on the left with
          blanks or zeros.  A - overrides a 0 if both are given.

相关内容