本文转载至:http://www.arachnoid.com/linux/beautify_bash/
Introduction
I wrote a Ruby beautifier script a few years ago and it has become very popular. I decided to rework it to beautify Bash scripts, even though I realized that Bash shell scripts are much more free-form than Ruby programs. This project is the result — a Bash script beautifier written in Ruby.
I have tested the script on a lot of typical Linx scripts, both my own and from the system. While testing I have reluctantly come to the conclusion that there are too many perverse ways people write Bash scripts for this program to ever correctly beautify 100% of submitted scripts. Maybe 99%, but never 100%.
One thing I noticed repeatedly is that people get in a hurry and leave off a terminating token within case ... esac statements, like this:case $x in a) # code for a ;; b) # code for b ;; c) # code for c esac
Notice the missing ';;' after "c)"? I found many cases like this, so I created a workaround, since even though it is syntactically incorrect it's obvious that Bash accepts it.
Another common problem, one that I ended up managing on a case-by-case basis, is the frequent use of Bash keywords as variable names, in particular the word "done". I found an example like this:
done=3;echo done;done
Obviously this is the work of someone who hates his life and his job, but I managed to process most of these deviant cases, for the same reason — Bash accepts them.
Another perversity is a Bash script than contains within it a huge binary section, somehow grafted onto the script in such a way that a single download contains an installation shell script plus a binary installation block. But the border between the two is not clearly or consistently made, so it's just not possible to process one of these.
So I offer this warning — this program isn't going to be able to process all Bash scripts with equal efficiency, and as to a binary script, it might scramble it. The program makes a backup copy before overwriting the original script, so you can recover in most cases, but do be careful with this script. It is well-behaved and error-free when processing the majority of shell scripts, but there is a small percentage of scripts with such bizarre structure than it can't do a very good job.
To use the script, download the plain-text version below, rename it "beautify_bash.rb", make it executable and put it (or a copy, or a symlink) in /usr/local/bin. Then invoke it in one of these ways:
$ beautify_bash.rb (list of filenames) $ beautify_bash.rb - < input_file > output_file
- Click here for a plain-text copy of the Ruby script
- Click Here for a pretty-printed version
- Version 1.2 09/10/2009. Fixed a user-reported bug having to do with quoted here-doc tags.
- Version 1.1 10/22/2008. Added some error-printing code for the all-too-common case of unbalanced tokens.
- Version 1.0 10/22/2008. Initial Public Release.