在 Bash 脚本 printf 命令中缩进而不在输出中出现缩进

问题描述 投票:0回答:3

我想在 bash 脚本中缩进,以便我的脚本看起来更有条理,但不希望打印空格。

如果我有命令

printf "<image>
        <<include etc/image.conf>>
        </image>" > file.txt

我希望 file.txt 看起来像

<image>
<<include etc/image.conf>>
</image>

而不是

<image>
        <<include etc/image.conf>>
        </image>

问题是我不希望我的脚本看起来像这样

While Loop
      If Statement
                printf "<image>
<<include etc/image.conf>>
</image>" > file.txt
                Command Here
      End If
End While

我只是想让它看起来更整洁一点

bash printf indentation
3个回答
5
投票

使用定界文档:

cat <<- EOF > file.txt
    <image>
    <<include etc/image.conf>>
    </image>
EOF

(注意:缩进应该是制表符:硬制表符是缩进的正确选择的又一个原因。)您可以在缩进中使用任意数量的制表符,它们将在传递给

cat
之前被 bash 删除。缩进也被分隔符去掉,所以你的最终结果将如下所示:

While Loop
      If Statement
                cat <<- EOF > file.txt 
                        <image>
                        <<include etc/image.conf>>
                        </image>
                EOF
                Command Here
      End If
End While

注意,这会对文本进行变量扩展等。如果您想避免这种情况,只需引用分隔符即可。例如,

cat <<- 'EOF' > file.txt


1
投票

为了使脚本更具可读性并防止空格妨碍:

printf "%s\n%s\n%s\n" "<image>" \
                      "<<include etc/image.conf>>" \
                      "</image>" > file.txt

0
投票

我发现 printf 的

%b
格式说明符明确使用
\n
作为平衡预期输出与脚本源代码可读性的最实用的解决方案。

来自

man printf

   %b    ARGUMENT as a string with '\' escapes interpreted,
         except that octal escapes are of the form \0 or \0NNN

因此,您的代码可能会修改为:

printf "%b" \
    "<image>\n"\
    "<<include etc/image.conf>>\n"\
    "</image>"

[注意:续行

\
不是强制性的,这只是我个人的偏好,以视觉方式对齐多行字符串。]

由于隐式字符串连接,

ARGUMENT
可以包含任意数量的行,而无需在格式说明符中计算和包含那么多
\n

当 printf 本身缩进时(例如,由于位于 if、switch 或 for 块内),这会更有帮助。


PS:我知道这个问题很老了,但它恰好是最热门的搜索结果之一,所以我认为这对从搜索引擎到达这里的其他人会有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.