LDP/LDP/guide/docbook/abs-guide/ex62.sh

30 lines
996 B
Bash
Raw Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
2012-11-27 14:56:18 +00:00
# ex62.sh: Global and local variables inside a function.
2001-07-10 14:25:50 +00:00
func ()
{
2003-11-03 16:25:16 +00:00
local loc_var=23 # Declared as local variable.
echo # Uses the 'local' builtin.
2002-01-07 15:24:19 +00:00
echo "\"loc_var\" in function = $loc_var"
2003-11-03 16:25:16 +00:00
global_var=999 # Not declared as local.
2012-11-27 14:56:18 +00:00
# Therefore, defaults to global.
2002-01-07 15:24:19 +00:00
echo "\"global_var\" in function = $global_var"
2001-07-10 14:25:50 +00:00
}
func
2012-11-27 14:56:18 +00:00
# Now, to see if local variable "loc_var" exists outside the function.
2001-07-10 14:25:50 +00:00
echo
2002-01-07 15:24:19 +00:00
echo "\"loc_var\" outside function = $loc_var"
2003-11-03 16:25:16 +00:00
# $loc_var outside function =
# No, $loc_var not visible globally.
2002-01-07 15:24:19 +00:00
echo "\"global_var\" outside function = $global_var"
2003-11-03 16:25:16 +00:00
# $global_var outside function = 999
2002-01-07 15:24:19 +00:00
# $global_var is visible globally.
echo
2001-07-10 14:25:50 +00:00
exit 0
2003-11-03 16:25:16 +00:00
# In contrast to C, a Bash variable declared inside a function
2012-11-27 14:56:18 +00:00
#+ is local ONLY if declared as such.