Funcs

Functions In Bash

  • Vars assigned outside of functions can be overwritten in functions and display aberrant results if local isn't used.
foo="bar"
echo "top level: $foo"

main(){
	foo="func bar"
	echo "func $foo"
}
main
echo "end $foo"

# OUTPUT:
#> top level: bar
#> func func bar
#> end func bar

#===#===#===#===#===#===#

foo="bar"
echo "top level: $foo"

main(){
	local foo="func bar"
	echo "func $foo"
}
main
echo "end $foo"

# OUTPUT:
#> top level: bar
#> func func bar
#> end bar
  • Do not use the function keyword, it reduces compatibility with older versions of bash.
# Right.
do_something() {
	# ...
}

# Wrong.
function do_something() {
	# ...
}
# Current function.
"${FUNCNAME[0]}"

# Parent function.
"${FUNCNAME[1]}"

# So on and so forth.
"${FUNCNAME[2]}"
"${FUNCNAME[3]}"

# All functions including parents.
"${FUNCNAME[@]}"

Backlinks