unset bash function variable with non-standard name

3.6k Views Asked by At

I may have this function in a bash script that gets sourced to the shell

function suman{
     echo "using suman function"
}

if I call

unset suman

things seem to work as expected

however if I have this as my function:

function suman-inspect {
     echo "using suman-inspect function"
}

then if I call

unset suman-inspect

or

unset "suman-inspect"

I get this message:

bash: unset: `suman-inspect': not a valid identifier

How can unset this variable as is?

2

There are 2 best solutions below

3
Alexander Mills On BEST ANSWER

After some more research, it appears that

unset -f "suman-inspect"

will work. This is surprising because unset suman did work, and did successfully unset the suman function (as far as I could tell).

0
cdarke On

Bash allows functions with names which are not valid identifiers to be created when not in posix mode.

So:

set -o posix
function suman-inspect { echo "using suman-inspect function"; }

Gives:

bash: `suman-inspect': not a valid identifier

ruakh makes a valid point by quoting man bash. The source code (builtins/set.def) has the comment: Posix.2 says try variables first, then functions, but ...

The POSIX standard says If neither -f nor -v is specified, name refers to a variable; if a variable by that name does not exist, it is unspecified whether a function by that name, if any, shall be unset.

So actually the behaviour is that old standby "unspecified*. If anything, the error is in the bash documentation. But to be fair, elsewhere in man bash it says:

A function definition may be deleted using the -f option to the unset builtin.