Bash Lessons

bash notetoself rbenv grokking

01|14|2012

Disclaimer 1: before all the haters talk: I'm not that well versed with bash (something I'm going to correct in year 2012 though.

Disclaimer 2: I discovered most of the commands / lessons here while trying to peruse the source of rbenv line by line, and grokking each and every command. Credits goes to sam stephenson of course.

Just to give a quick summary of the different commands I'm going to discuss, here they are in order:

set -e
[ -n "$FOO"] && do_command
set -x
type -p command1 command2
head -1
local foo

Lesson 0:

 set -e

"Every script you write should include this at the top". This makes the script terminate as soon as a single error is encountered.

Lesson 1:

This idiom allows you to conditionally execute a specific command if a certain variable is set (an empty string doesn't count)

[ -n "$FOO" ] && do_command

Lesson 2:

If you want to trace what's happening in a bash script, simply do

set -x

This prints out commands as they are evaluated. See the manpage for more details.

Lesson 3:

How to display the locations of different commands. Let's say you want to print out where ruby, ri, and irb are located in order, you can simply do:

type -p ruby ri irb

Lesson 4:

Extract the first line of a file:

head -1 file

If we wanted to get the first line of the previous example type -p, we simply do:

type -p ruby ri irb | head -1

Lesson 5:

Use local when declaring functions. Like most programming languages, you may be surprised to know that bash also supports local variables.

Simply declare all your variables in your functions to make use of this.

local cwd="$(pwd)"

It's worth pointing out that declare is pretty much a super set of local (correct me if I'm wrong on this?).

Sources:

http://www.davidpashley.com/articles/writing-robust-shell-scripts.html http://ss64.com/bash/set.html http://ss64.com/bash/declare.html http://ss64.com/bash/local.html

blog comments powered by Disqus