Modular Shells


I do a fair amount of work on the command line, but didn’t really dig into shell scripting until recently. It came up in the context of making my .bashrc (“Bourne shell run commands”) and .zshrc (Z shell run commands”) files more modular, and once I learned a bit about it, I was hooked.

The rc file for your shell (I’ll assume bash from here on out) can contain all kinds of useful commands and functions for improving your development environment. (My .bashrc file is here.) For awhile, I put all my environment variables in my .bashrc file; while that worked, it rapidly cluttered it up. Then I downloaded bash-completion (if you have Homebrew, you can just type brew install bash-completion) and found that you could source the necessary file without including everything directly in the .bashrc file (with source ~/.git-prompt.sh). And that got me thinking: why not group environment variables and functions in their own files, then source them as needed?

I haven’t yet pushed my newest .bashrc file to GitHub, so these examples aren’t available there, but the two most interesting uses I’ve found are for the environment variables in this site (for logging in and writing posts) and grouping useful bash utilities. For example, if you have the following .website file:

And you source it in your .bashrc file:

Then you could write this in your website code (assuming you’re using Ruby):

(Theoretically you would use your password for authentication, which isn’t shown here.) Ruby’s built-in ENV checks for the named variable in the environment, and returns nil if it can’t find it (documentation available here).

You can also use this modularization to source useful scripts, this one:

The up() function allows you to move up a directory quickly; if you’re nested five levels deep in a folder, typing up 5 will get you back to the top. To use it, just source ~/up.sh (assuming the file is in your home directory) in your .bashrc file.

I’m just scratching the surface of using configuration files and shell scripting to make life easier, but I’m already really excited about it. I’ll post any interesting/useful scripts (whether I find them or create them myself) as they come up.