Parentheses are optional. From Bash Reference Manual --> 3.3 Shell Functions:
Functions are declared using this syntax:
name () compound-command [ redirections ]
or
function name [()] compound-command [ redirections ]
This defines a shell function named name. The reserved word function
is optional. If the function
reserved word is supplied, the
parentheses are optional. The body of the function is the compound
command compound-command (see Compound Commands). That command is
usually a list enclosed between { and }, but may be any compound
command listed above. compound-command is executed whenever name is
specified as the name of a command. When the shell is in POSIX mode
(see Bash POSIX Mode), name may not be the same as one of the special
builtins (see Special Builtins). Any redirections (see Redirections)
associated with the shell function are performed when the function is
executed.
So these are equivalent:
function hello {
echo "hello there"
}
hello () {
echo "hello there"
}
In Bash, functions can access global variables normally, so that the approach is slightly different from other languages. Normally, there is no need to use return
because there is no value to catch.
See an example. Here, we have a global variable myvar
containing a value. In the functions mytest
and mytest_inner
we are changing its value. However, in one case the value affects the global environment, whereas in the other does not.
In mytest
we change the value and it affects the main block. In mytest_inner
we do the same, but the value is just changed locally, in the sub-shell running in the function.
#!/bin/bash
function mytest {
echo "mytest -> myvar: $myvar"
((myvar++))
}
function mytest_inner () {
(
echo "mytest_inner -> myvar: $myvar"
((myvar++))
)
}
myvar=$1
mytest
echo "main -> myvar: $myvar"
mytest_inner
echo "main -> myvar: $myvar"
Let's run it:
$ ./myscript.sh 20
mytest -> myvar: 20
main -> myvar: 21
mytest_inner -> myvar: 21
main -> myvar: 21