Discussion:
[Help-bash] distinguish local function and global function
Peng Yu
2018-03-05 17:17:17 UTC
Permalink
The following example shows that a local function can be defined
within a function. But `type` (as the way that I use it) cannot
distinguish them. Is there a way to tell what functions are local and
what are global?

$ cat main_x1.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

set -v
function cmd {
function cmd1 {
echo xxx
}
type cmd1
cmd1
}

type cmd
cmd
$ ./main_x1.sh
function cmd {
function cmd1 {
echo xxx
}
type cmd1
cmd1
}

type cmd
cmd is a function
cmd ()
{
function cmd1 ()
{
echo xxx
};
type cmd1;
cmd1
}
cmd
cmd1 is a function
cmd1 ()
{
echo xxx
}
xxx
--
Regards,
Peng
Nick Chambers
2018-03-05 17:21:29 UTC
Permalink
Functions, much like variables are only always global. ie

NickChambers-iMac:~ Nick$ foo() {
bar=2 # global bar
}
NickChambers-iMac:~ Nick$ baz() {
boo() { echo 'Hello, world!'; } # global boo
}
NickChambers-iMac:~ Nick$ foo
NickChambers-iMac:~ Nick$ echo "$bar"
2
NickChambers-iMac:~ Nick$ baz
NickChambers-iMac:~ Nick$ boo
Hello, world!
NickChambers-iMac:~ Nick$

As far as I know, you can't have a local function like you can a
variable. They're only always global. You could create one in a
subshell, but I'm not sure if that's really what you're after.
The following example shows that a local function can be defined
within a function. But `type` (as the way that I use it) cannot
distinguish them. Is there a way to tell what functions are local and
what are global?
$ cat main_x1.sh
#!/usr/bin/env bash
set -v
function cmd {
function cmd1 {
echo xxx
}
type cmd1
cmd1
}
type cmd
cmd
$ ./main_x1.sh
function cmd {
function cmd1 {
echo xxx
}
type cmd1
cmd1
}
type cmd
cmd is a function
cmd ()
{
function cmd1 ()
{
echo xxx
};
type cmd1;
cmd1
}
cmd
cmd1 is a function
cmd1 ()
{
echo xxx
}
xxx
--
Regards,
Peng
Chet Ramey
2018-03-05 19:22:49 UTC
Permalink
Post by Peng Yu
The following example shows that a local function can be defined
within a function.
There are no such things as `local' functions. All functions exist at
the global scope.
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU ***@case.edu http://tiswww.cwru.edu/~chet/
Loading...