在 Bash 脚本 printf 命令中缩进而不在输出中出现缩进
Indenting in a Bash script printf command without the indent coming out in the output
我想在我的 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
我只是想让它看起来更整洁一点
为了使脚本更具可读性并防止空格妨碍:
printf "%s\n%s\n%s\n" "<image>" \
"<<include etc/image.conf>>" \
"</image>" > file.txt
使用 heredoc:
cat <<- EOF > file.txt
<image>
<<include etc/image.conf>>
</image>
EOF
(注意:缩进应该是制表符:硬制表符是缩进的正确选择的另一个原因。)您可以在缩进中使用任意数量的制表符,它们将被 bash 剥离在传递给 cat
之前。缩进也被定界符剥离,因此您的最终结果将如下所示:
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
我想在我的 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
我只是想让它看起来更整洁一点
为了使脚本更具可读性并防止空格妨碍:
printf "%s\n%s\n%s\n" "<image>" \
"<<include etc/image.conf>>" \
"</image>" > file.txt
使用 heredoc:
cat <<- EOF > file.txt
<image>
<<include etc/image.conf>>
</image>
EOF
(注意:缩进应该是制表符:硬制表符是缩进的正确选择的另一个原因。)您可以在缩进中使用任意数量的制表符,它们将被 bash 剥离在传递给 cat
之前。缩进也被定界符剥离,因此您的最终结果将如下所示:
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