Friday, 18 August 2017

Bash Function

Cited from the Book "Pro Bash Programming"

A function is executed in the same process as the script that calls it. This makes it fast, because no new process has to be created. All the variables of the script are available to it without having to be exported, and when a function changes those variables, the changes will be seen by the calling script. That said, you can make variables local to the function so that they do not affect the calling script; the choice is yours.

name() <compound command>

function name() <compound command>

Inside a function, an argument sets the function’s return code; if there is no argument, the exit code of the function defaults to that of the last command executed.

The next command, local, is a shell builtin that restricts a variable’s scope to the function (and its children), but the variable will not change in the parent process.

Beginning with bash-4.0, local and declare have an option, -A, to declare an associative array.

After a script containing only a function is run/sourced, the function is now available at the shell prompt.

If a function’s body is wrapped in parentheses, then it is executed in a subshell, and changes made during its execution do not remain in effect after it exits:

$ funky() ( name=nobody; echo "name = $name" )
$ name=Rumpelstiltskin
$ funky
name = nobody
$ echo "name = $name"
name = Rumpelstiltskin

max3() { #@ Sort 3 integers and store in $_MAX3, $_MID3 and $_MIN3
  [ $# -ne 3 ] && return 5
  [ $1 -gt $2 ] && { set -- $2 $1 $3; }
  [ $2 -gt $3 ] && { set -- $1 $3 $2; }
  [ $1 -gt $2 ] && { set -- $2 $1 $3; }
  _MAX3=$3
  _MID3=$2
  _MIN3=$1
}

Use the convention of beginning function names with an underscore when they set a variable rather than print the result. The variable is the name of the function converted to uppercase.

Most of the time, it is recommended to source the library to include all its functions in the current script:

. date-funcs ## get date-funcs from:
## http://cfaj.freeshell.org/shell/ssr/08-The-Dating-Game.shtml

Occasionally, only one function is needed from a library, so it is recommended to cut and paste it into a new script.


No comments:

Post a Comment