Bash Functions

Creating Functions...


function myFunction { #<-- There must be a space between the name and the curly brace } myFunction() { }

In Bash functions can be created in one of two ways...

Way One:



Way Two:



CREATED 2012-11-18 18:18:23.0

00-17-E3

UPDATED 2017-07-28 17:20:28.0

Functions Can Not be Empty...


myFunction(){ } ./myScript.sh: line 5: syntax error near unexpected token `}' myFunction(){    # This is my function... }

Bash Functions can not be empty even with comments...


will give a compiler error...

Even if it has comments inside of it...



CREATED 2017-07-28 17:21:18.0

00-2A-2C

UPDATED 2017-07-28 17:27:29.0

One Liners...


myFunction() { echo "This is my function!;"} ./test.sh: line 14: syntax error: unexpected end of file

In bash Functions can be written on one line. But - there is a catch...

The last command must have a tailing semi-colon (;). Without it the compiler gives an error...

CREATED 2017-07-28 17:27:38.0

00-2A-2D

UPDATED 2017-07-28 17:27:49.0

Pre-declared...


myFunction() {
   echo "This is my function" } myFunction
./myScript.sh: line 11: myFunction: command not found if [ "$USER" = kennyl ]
then
   greet(){       echo "${USER} is great!"
   }
else
   greet(){
      echo "Hello ${USER}"
   }
fi

In bash a Function must be declared before the first reference to it.



If the call to myFunction was fist, the compiler will complain...

By the same token, functions can be declared anywhere. As long as the reference to it comes after the function.


CREATED 2017-07-28 17:32:44.0

00-2A-2E

UPDATED 2017-07-28 17:33:01.0

Nesting...


myFunction(){
   echo "myFunction"
   myInnerFunction(){
      echo "This is my Inner Function."
   }
}
./myScript.sh: line 18: myInnerFunction: command not found myFunction myInnerFunction myFunction This is my Inner Function

In bash Functions can be nested - but - there's another catch...

The Catch: to access myInnerFunction you need to call myFunction first. In this scenario, if you called myInnerFunction first you would get...

but if you call myFunction first, it would expose myInnerFunction which could then be called.


would produce...


CREATED 2017-07-28 17:38:52.0

00-2A-2F

UPDATED 2017-07-28 17:38:59.0

Knowledge

L
I
N
K
S

DBID: db.wam

Page Server: Ithica

©2012 Leistware Data Systems

      Hello anonymous