bash 的代码格式化程序/美化程序(在命令行中)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12046886/
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-18 03:05:04  来源:igfitidea点击:

Code formatter / beautifier for bash (in command line)?

bashcommand-linecode-formatting

提问by Yauhen Yakimovich

Looking for a command line code formatter that can be used for bashcode. It must be configurable and preferably usable from command line.

寻找可用于bash代码的命令行代码格式化程序。它必须是可配置的,并且最好可以从命令行使用。

I have a big project in bash, which I need to use Q in mind for. So far I am happy with a program written in pythonby Paul Lutus (a remake of his previous version in Ruby).

我在 bash 中有一个大项目,我需要牢记使用 Q。到目前为止,我对Paul Lutus用Python编写的程序感到满意(对他以前用 Ruby编写的版本的重制版)。

See http://arachnoid.com/python/beautify_bash_program.html(also cloned here https://github.com/ewiger/beautify_bash).

请参阅http://arachnoid.com/python/beautify_bash_program.html(也在此处克隆https://github.com/ewiger/beautify_bash)。

but I would like to learn any serious alternative to this tool if it exists. Requirements: it should provide robust enough performance and behavior of treating/parsing rather complicated code.

但我想学习这个工具的任何严肃的替代品,如果它存在的话。要求:它应该提供足够强大的性能和处理/解析相当复杂代码的行为。

PS I believe full parsing of bash code is generally complicated because there exists no official language grammar (but please correct me if I am wrong about it).

PS 我相信 bash 代码的完整解析通常很复杂,因为不存在官方语言语法(但如果我错了,请纠正我)。

采纳答案by drizzt

you can script vim to do: "gg=G" that means "indent all the file"

你可以编写 vim 来做:“gg=G”,意思是“缩进所有文件”

回答by Daniel Martí

You could give shfmta try. It implements its own shell parser including Bash support, so it's more robust than plaintext-based tools.

你可以试试shfmt。它实现了自己的 shell 解析器,包括 Bash 支持,因此它比基于纯文本的工具更健壮。

And both the parser and printer are available as Go packages, so it should be easy to write a 20-line Go program to manipulate or play with shell code.

解析器和打印机都可以作为 Go 包使用,因此编写一个 20 行的 Go 程序来操作或使用 shell 代码应该很容易。

Please note that I'm the author, so the advice may be a bit biased :)

请注意,我是作者,所以建议可能有点偏见:)

回答by bas080

I discovered that the typebuiltin will print functions in a formatted manner.

我发现type内置函数会以格式化的方式打印函数。

#/usr/bin/env bash

source <(cat <(echo 'wrapper() {') - <(echo '}'));
type wrapper | tail -n +4 | head -n -1 | sed 's/^    //g'

https://github.com/bas080/flush

https://github.com/bas080/flush