Search code examples
shellposix

Is a conditional function definition allowed in POSIX compliant shell scripts?


In Bash and KornShell (ksh), I see the following script works fine.

if [ -n "foo" ]
then
    foo()
    {
        echo function foo is defined
    }
else
    bar()
    {
        echo function bar is defined
    }
fi

foo
bar

It also generates the expected output when executed.

$ bash scr.sh
function foo is defined
scr.sh: line 15: bar: command not found

$ ksh scr.sh
function foo is defined
scr.sh: line 15: bar: not found

I want to know if this script would run and generate this output on any POSIX conformant shell.


Solution

  • I agree with your reading of the grammar. A function definition may occur in the body of an if statement, making its execution conditional.