shell programming - functions

created onJanuary 18, 2022

general form

funcname () { # code goes here }

invocation

funcname

return values

a shell script function can’t return anything else apart from an exit status, that is, an integer value. but there are workarounds for returning others values like strings.

returning exit status

function:

funcname () { # some code that sets value of variable 'exitStatus' return ${exitStatus} }"

invocation:

funcname somevar=$?

printf or echo in function

function:

funcname () { # some code that sets value of variable 'var' echo ${var} }

invocation:

somevar=$( funcname )

the problem with this workaround is that anything that gets spit out to stdout and stderr end ups in ‘somevar’. you might need to set stderr to an other output channel like /dev/null.

shared variable

the shared variable has to be declared before the declaration of the function.

shared variable and function:

sharedVar="" funcname () { # some code to set value of 'sharedVar' }

invocation:

funcname # some code to process 'sharedVar'