Notes on shell scripting
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:
PHP_BINPATH=
if [ $PHP_BINPATH == "foo" ]
then
echo "It's foo"
fi
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:
PHP_BINPATH=
if [ "$PHP_BINPATH" == "foo" ]
then
echo "It's foo"
fi
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'!
