blog.minskio.co.uk

Content and theme behind minskio.co.uk
Log | Files | Refs

formatting-and-checking-bash-scripts.md (1495B)


      1 ---
      2 title: "Formatting and checking bash scripts"
      3 date: 2022-02-01T11:52:00
      4 lastmod: 2022-02-01T11:52:00
      5 tags: ["Linux", "Software", "Snippets"]
      6 ---
      7 
      8 Everyone's head of [shellcheck](https://github.com/koalaman/shellcheck) for checking over scripts to ensure obvious (and not-so-obvious) mistakes aren't being made. Afterwards I usually quite like to beautify/prettify/format up code to get all the usual readability improvements gained from this. In the past, I've used [beautysh](https://github.com/lovesegfault/beautysh) and while it's worked, I generally don't like using python programs when alternatives are available, and especially don't like manually installing programs when it can be done via the package manager. In steps [shfmt](https://github.com/mvdan/sh), a handy go program (no dependencies, portable, etc) that works exactly how you'd expect it to be run.
      9 
     10 It can either be installed via [your package manager](https://github.com/mvdan/sh#readme), or you can install it from source using go:
     11 ```
     12 go install mvdan.cc/sh/v3/cmd/shfmt@latest
     13 ```
     14 
     15 Once installed, test it's runnable
     16 ```
     17 shfmt --version
     18 ```
     19 
     20 With that confirmed, you can run it against a bash script as such:
     21 ```
     22 shfmt -l -d path/to/your/script.sh
     23 ```
     24 
     25 In the above example, the `-l` flag formats the text and the `-d` flag shows a diff of what's been changed.
     26 If you're happy with the changes shown, you can replace the `-d` flag with `-w` to overwrite the original file:
     27 
     28 ```
     29 shfmt -l -w path/to/your/script.sh
     30 ```