bash shell 脚本的漂亮打印

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3987382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:48:20  来源:igfitidea点击:

Pretty-print for shell script

bashscriptingshellindentation

提问by PeterMmm

I'm looking for something similiar to indentbut for (bash) scripts. Console only, no colorizing, etc.

我正在寻找类似于缩进但用于(bash)脚本的东西。只有控制台,没有着色等。

Do you know of one ?

你知道一个吗?

回答by Benoit

Vim can indent bash scripts. But not reformat them before indenting.
Backup your bash script, open it with vim, type gg=GZZand indent will be corrected. (Note for the impatient: this overwrites the file, so be sure to do that backup!)

Vim 可以缩进 bash 脚本。但在缩进之前不要重新格式化它们。
备份你的 bash 脚本,用 vim 打开它,键入gg=GZZ和缩进将被更正。(不耐烦的注意:这会覆盖文件,所以一定要备份!)

Though, some bugs with <<(expecting EOF as first character on a line) e.g.

虽然,一些错误<<(期望 EOF 作为一行的第一个字符)例如

EDIT: ZZ not ZQ

编辑:ZZ 不是 ZQ

回答by Daniel Martí

A bit late to the party, but it looks like shfmtcould do the trick for you.

聚会有点晚了,但看起来shfmt可以为您解决问题。

回答by Zibri

In bash I do this:

在 bash 我这样做:

reindent() {
source <(echo "Zibri () {";cat ""; echo "}")
declare -f Zibri|head --lines=-1|tail --lines=+3 | sed -e "s/^\s\s\s\s//"
}

this eliminates comments and reindents the script "bash way".

这消除了注释并重新缩进脚本“bash 方式”。

If you have HEREDOCS in your script, they got ruined by the sed in the previous function.

如果您的脚本中有 HEREDOCS,它们就会被前一个函数中的 sed 破坏。

So use:

所以使用:

reindent() {
source <(echo "Zibri () {";cat ""; echo "}")
declare -f Zibri|head --lines=-1|tail --lines=+3"
}

But all your script will have a 4 spaces indentation.

但是你所有的脚本都会有一个 4 个空格的缩进。

Or you can do:

或者你可以这样做:

reindent () 
{ 
    rstr=$(mktemp -u "XXXXXXXXXX");
    source <(echo "Zibri () {";cat ""|sed -e "s/^\s\s\s\s/$rstr/"; echo "}");
    echo '#!/bin/bash';
    declare -f Zibri | head --lines=-1 | tail --lines=+3 | sed -e "s/^\s\s\s\s//;s/$rstr/    /"
}

which takes care also of heredocs.

这也照顾heredocs。