Using Bash Functions To Start A Local Environment Quicker

Colin Lord
3 min readJun 27, 2017

--

I can never remember what command(s) to type in Terminal to start my local development environments. Even after a few months on a project, I’m always going back to my documentation after every reboot or update. It’s definitely a #firstworldproblem but there has to be a better way than a Google doc and copy/paste.

There is. Let’s write some bash functions.

Open your terminal and type the following to get into your .bash_profile so we can write a function or two:

nano ~/.bash_profile

Here’s a simple example. When I’m working on my company’s website, Modea.com, I need to cd into the project repo and then run rails server. This is how I’d do it with one function instead.

We’re going to create a function named modeaServer and then put each command on its own line. For this basic example, we won’t need any parameters.

modeaServer () {
cd ~/Repos/Modea.com-3.0/
rails server
}

Once you’re happy with what’s in your bash_profile, type ^X to save your file and then run the following to load your new changes.

source ~/.bash_profile

Now whenever I want to start my local instance of Modea.com, I just type “modeaServer” into Terminal and I’ll be good to go.

What about a more complex example with a parameter?

foo() {
echo "Parameter #1 is $1"
}

If I typed “foo bar” into my terminal, I’d get back “Parameter #1 is bar”. If I needed a second parameter, I’d write $2 inside my function.

You could use parameters in a number of different ways. If you have a number of different sites that are started the same way, you could write one function and make the parameter the directory.

start () {
cd ~/Repos/$1/
rails server
}

In this example, you would type start and then the name of your directory. “start site1” would run rails server inside the site1 directory.

Side note: .bash_profile isn’t the only place you can store these functions. You could also use .bashrc instead depending on your particular needs. While .bash_profile is executed for login shells, .bashrc is executed for interactive non-login shells.

I’ve been a big fan of Panic’s Coda 2 for most of my development work. One of the reasons why is that I can have terminal open as a tab along with the rest of my other files. I need to store my functions in .bash_profile for Coda to be able read them. Otherwise, I could use .bashrc instead.

Here’s an example of typing modeaServer to boot my local environment inside of Coda 2.

This obviously is just scratching the surface of what you could do with these functions. You can do a lot more with them than just starting local environments. But if you juggle multiple projects, do yourself a favor and spend 10 minutes setting some functions up!

--

--

Colin Lord

Meteorologist turned front-end engineer. Married to @katyrae87. Born in Atlanta. Educated at @FloridaState. Now living in Music City, Tennessee.