Notes on shell scripting

published on December 29, 2011.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Yesterday I did some shell scripting and thought about writing down the few things learned along the way. Amazing how little needs to be done to learn a lot :)

Result of a command to a variable

First thing I learned is how to “save” the result of a shell command to a local variable:

PHP_BINPATH=$(which php)

By enclosing the command in parenthesis and putting a dollar sign in front of it, will put the result of that command in the variable.

An empty variable

Turns out, a variable can be empty, null. Nothing strange with that, until one tries to do something with that variable. For example:

if [ $PHP_BINPATH == "foo" ]
    echo "It's foo"

will die with a strange error: “line 2: [: =: unary operator expected”. Problem is that when evaluating it will see if [ == “foo” ] and turns out [ is some reserved command or some such. The fix is to wrap $PHP_BINPATH in double quotes:

if [ "$PHP_BINPATH" == "foo" ]
    echo "It's foo"

Pass all the arguments!

When calling some other command from within the shell script, and all the arguments which are passed to the shell script need to be passed to that other command, use ”$@” for that:

$PHP_BINPATH usher.php "$@"

This will pass all the arguments to the PHP script which is called from within the shell script.

Happy hackin’!

Thanks for reading! If you require help on a project of any kind, let's talk!

Robert Basic

Robert Basic

Software engineer, consultant, open source contributor.

Let's work together!

If you require outsourcing or consulting help on your projects, I'm available!

Robert Basic © 2008 — 2019
Get the feed