How to auto format code from the command line?

If you like vim you can invoke its action from the command-line.

echo -e "G=gg\n:wq\n" | vim ./myfile.php 

Warning the above command will modify your file without prompting. Do a backup before.
It's possible to find examples integrated with find to accomplish the same work on a bunch of files [0].

Looking beyond it's possible to find a lot of utilities build for this, and this number will continue to grow in time; you can search for their updated versions on internet and you can start for example from:

  • Artistic Style [1], astyle, for C, C++, C++/CLI, Objective‑C, C# and Java programming languages.
  • tidy [2] for Html
  • IDE solutions invoked by command line starting from kate [3] for which there exists just made plug-in; you can built your own indentation scripts [4] too, continuing with UniversalIndentGUI [5], eclipse [5]...

vim -c "execute 'normal! =G' | :wq! out.js" input.js

You can also use the alternative syntax + instead of -c. It's the same.

vim +"execute 'normal! =G' | :wq! out.js" input.js
  1. It executes the normal command =G, which will autoformat/indent (=) every line until the end of the file (G).

  2. Then :wq! out.js writes it to a file and quits vim. If you just want to overwrite the same file, then remove the out.js.

Also, you need to have this line in your ~/.vimrc in order for the autoformat indent plugin to work:

filetype plugin indent on