使用bash printf正确地换行列的方法

4

我使用printf编写了一个bash脚本的使用函数,但是它非常繁琐,我想肯定有比我做的更简单的方法。我很好奇它是什么,这样我就可以在下一次改进它(下面只显示了2个参数以说明问题)。

这是代码本身:

 usage(){
    printf "\n\e[1m%s\x1b[0m %-5s\n" "USAGE:" "Blah Blah"
    printf "%7s \e[1m%-15s\x1b[0m %s %s\n" "" "-h" "[Optional]" "Display usage information"
    printf "%7s \e[1m%-15s\x1b[0m %s %s" "" "-ofps" "[Optional] Number of output frames per second"
    printf "%-34s %s\n" "" "Applies to the *output* video frame rate."
    exit 1
}

输出的样式如下:

USAGE: Blah Blah
       -h        [Optional] Display usage information
       -ofps     [Optional] Number of output frames per second                                               
                            Applies to the *output* video frame rate.

如果有一种方法可以指定右侧“列”中的字符串在整行长度超过80个字符时换行(并保留缩进),那将是我要寻找的功能。我对纯bash解决方案感兴趣,但特别是在仍然使用printf的情况下最容易实现的方法。
1个回答

4

以下是我通常执行Usage命令的方式,它不使用printf,但它是有效的。(我也使用tput代替原始转义序列。请查看tput(1)terminfo(5)手册以获取详细信息)

Usage="Blah Blah [-options...]

  options
  $(tput bold)-h$(tput sgr0)       Display usage information
  $(tput bold)-o<fps>$(tput sgr0)  Number of output frames per second
           Applies to the *output* video frame rate
"

然后,每当我想要打印它时,我输入以下内容:
echo 2>&1 "?Usage: $Usage";
exit 1

或其变体。如果您想要,可以在echo的结尾添加| fmt。这将为您进行自动换行。但通常,我只是在脚本开头,在#!/bin/env bash之后编写一个大型多行字符串,以充当内部文档和使用说明。


fmt 是我正在寻找的解决方案。干杯。 - paradroid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接