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

Viewed 34626

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

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 python by Paul Lutus (a remake of his previous version in Ruby).

See http://arachnoid.com/python/beautify_bash_program.html (also cloned here 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).

4 Answers

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

#/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

On the contrary the shell does have a rigorous grammar. It is described both in English in the ISO standard and documentation for Bash and other shells, and in formal terms in the shell.y file in the Bash source tree.

What makes it "hard" is that where one normally thinks of, say, a quoted string as single lexical token, In the shell every meta character is a separate lexical token, so the meaning of a character can change depending on its grammatical context.

So the parsing tokens do not align with the "shell words" that a user thinks of, and a simple quoted string is at least 3 tokens.

The implementations typically take some shortcuts involving using multiple lexical analysers chosen by whether the grammar is inside quotes, inside numeric context, or outside both.

Related