Categories
Development

Bash #4 – Quote function parameters

I try to extract stuff into functions both for re-use and encapsulation. Coming from Java Bash itself leaves a lot to be desired in this area but that´s a different post. What I´ve found is that if I don´t encapsulate input variables with quotes it can become quite confusing what is defined and not. If you don´t quote and a variable is unset, it will shift your input.

function myfunc() {
	local OPTION_ONE=$1
	local OPTION_TWO=$2

	echo "$OPTION_ONE and $OPTION_TWO"
}

VARTWO="hello"

myfunc $VARONE $VARTWO
myfunc "$VARONE" "$VARTWO"

In the first (unquoted) line above OPTION_ONE inside the functio will “become” VARTWO. In the second example with quotes it´s easier to understand that VARONE is the one missing, because it doesn´t shift it to the left.

Categories
Development OS tricks

Bash #3 – Default values

When handling parameters from the command line I usually want one or two parameters to have a default value. In Bash I can achieve this through:

DIRECTORY=${DIRECTORY_FROM_COMMAND_LINE:-"/tmp"}

Where “DIRECTORY_FROM_COMMAND_LINE” is just another variable and thus can be 1 (for $1).

Categories
Development OS tricks

Bash #2

Part of what I find really hard with Bash scripts is encapsulation and error handling. It all became a tiny bit better when I discovered how I can print the call stack when something occurs. Check out this blog post for how to print the call stack.

I’m thinking this fits nicely with trap, but I’ll have to try that another day. 🙂