Archive

Monthly Archives: January 2015

As a shell-pro you do not need support wheels. That is why you cannot give names to input arguments in bash. If you are soft you may give names to arguments inside the functions body.

logarithm () {
	X=$1 
	BASE=${2:-"10"}
	RESULT=$(echo "l($X)/l($BASE)" | bc -l )
 	echo $RESULT
}

The defined function logarithm outputs the logarithm of the first input with respect to the base given as second input. The latter is optional: its value is assigned to the variable BASE if the second input ($2) is provided, otherwise the default value 10 is used.

Many peoble tend to use the same fitting variable names inside and outside the function. A common way to solve resulting name conflicts is that, inside the functions body, you have to explicitly state it if want to refer to a variable that lives outside. Not so with bash.

BASE=2
A=$(logarithm 1000)
B=$(logarithm 8 $BASE)

We expect both the values of A and B to be 3. But the value of B is something else. The first call of logarithm changed the value of BASE. For protecting the outside BASE from being set within a function call we have to declare the variable BASE in the functions body as local. And you better do so if your function happens to use variable names like USER or PATH.

Advertisements