Tuesday, January 03, 2006

Functions Can Set Globals

The title says it all. Shell variables are global by default.
#!/bin/bash

fezmo=6
jo_mamma() {
fezmo=9
}

echo before call fezmo is $fezmo
jo_mamma
echo after call fezmo is $fezmo
That means that you have to keep track of the names of every variable you set in a function. Bummer. Shell scripts aren't typically very long, so this usually isn't a big deal. Still, using local inside functions is a good habit to get into.

#!/bin/bash

fezmo=6
jo_mamma() {
local fezmo=9
}

echo before call fezmo is $fezmo
jo_mamma
echo after call fezmo is $fezmo
(Don't just read these examples and nod your head. Use snarf-N-barf to try them.)

0 Comments:

Post a Comment

<< Home