Work Faster with Basic Shell Commands
Writing your own shell scripts may seem a little intimidating at first, but it’s actually quite simple and can drastically improve your workflow. Any sequence of commands you would run from the command line you can put into a shell script.
For example, when I want to start coding on a project, I usually end up opening my editor from the terminal and a new tab in my browser to view the project. This doesn’t take very long, but since it’s something I do multiple times every day, I figured I should try to automate it.
Let’s Scriptify It
I wanted to be able to pull up my editor and open the new browser tab right from the terminal so I came up with the following script to do just that:
# !/bin/sh
open -g 'http://localhost/chris-schmitz.com'
subl .
Breaking this down, here’s what each line does:
# !/bin/sh
– Invokes the shell, a standard starting line for a shell scriptopen -g 'http://localhost/chris-schmitz.com'
– Opens the URL for the project in a new tab of my default browsersubl .
– Opens the current directory in Sublime Text 2 (using TextMate the command would bemate .
)
Now, assuming I saved the file as open.sh, I can run sh open.sh
from the command line to open my editor and the browser tab. This was a great next step, but I thought I could do a little better.
A Shortcut for the Shortcut
I love TextExpander and any time I have text that I need to type on a regular basis I make a snippet for it. I figured this shell script is a perfect candidate for that.
I didn’t want to have to create a new file and then use a snippet to insert those three lines, so I use the following snippet to create the file with those three lines all in one step from the terminal.
echo "# !/bin/shnnopen -g 'http://localhost/%fill:site_name%'nsubl ." >; open.sh
It’s just a one-liner with some escaped characters and line breaks that get inserted into the open.sh file. I set the shortcut for the snippet to qlp, short for Quick Launch Project.
Now I can create these shell scripts with ease, but I still didn’t like having to type sh open.sh
all the time. I decided I wanted to make it shorter, so I aliased that to dev
with the following command:
alias dev='sh open.sh'
Note: I’m using ZSH in my terminal, but I believe this command is the same for Bash.
My New Workflow
Now when I create a new project, all I have to do to get setup is:
cd
to the directory- Expand my
qlp
snippet - Run the
dev
command, and I’m ready to go
The main takeaway from this shouldn’t be the actual code, but the idea of how easy it is to automate repetitive tasks. A few basic shell commands can go a long way.
If you want to learn more about shell scripting, I highly recommend the Bash Guide for Beginners.
Source: