How to pretty-print shell script code

How to pretty-print shell script code

Postby hbuhrmester » 30.12.2015, 14:53

This is a little trick, which I learned from a Wiki:

http://wiki.bash-hackers.org/scripting/style

It only works with functions, and it will delete all comments and empty lines. Shell expressions like $'\r' are interpreted as they should.

But it is still useful to quickly clean up some messy code:

  1. Copy all functions into a text file "messy-functions.txt":

    Code: Select all
    getwddefs()
    {
    wddefs="0"
    read -p "Download Microsoft Windows Defender definition files? [y/n] " addwddefs
    if [ "$addwddefs" == "y" ]; then
      wddefs="1"
      param7="/wddefs"
    fi
    }

  2. Source that file:

    Code: Select all
    $ source messy-functions.txt

  3. Display the function declarations with "type" or "declare -f". All functions will be pretty-printed by the shell itself. In this example, the indentation will be corrected to four spaces:

    Code: Select all
    $ type getwddefs
    getwddefs is a function
    getwddefs ()
    {
        wddefs="0";
        read -p "Download Microsoft Windows Defender definition files? [y/n] " addwddefs;
        if [ "$addwddefs" == "y" ]; then
            wddefs="1";
            param7="/wddefs";
        fi
    }
    $ declare -f getwddefs
    getwddefs ()
    {
        wddefs="0";
        read -p "Download Microsoft Windows Defender definition files? [y/n] " addwddefs;
        if [ "$addwddefs" == "y" ]; then
            wddefs="1";
            param7="/wddefs";
        fi
    }
When in bash, do as the bash does.
hbuhrmester
 
Posts: 245
Joined: 11.10.2013, 20:59

Return to Linux

Who is online

Users browsing this forum: Google [Bot] and 4 guests