views:

783

answers:

5

How can I determine if a function is already defined in a bash script?

I am trying to make my .bash_login script portable between systems, so I want to add logic to only call a function if it exists.

I want to add __git_ps1() to PS1 only if that function exists on that system. This funciton normally defined in git-completion.bash which comes with git source, or by one of the bash completion scripts that ports/apt installs.

+4  A: 

You can do it using:

type function_name

in will return your a function definition in case it exists. So you can check whenever output is empty or not.

PS. Even better I've just checked it will output that function is not exist otherwise output function body.

Artem Barger
+2  A: 
if type __git_ps1 >/dev/null 2>&1; then
    PS1=whatever
fi
chaos
Using `type` was much faster than `declare` -- thanks.
csexton
+1  A: 

declare -F 'function_name' > /dev/null

echo $?

$? result has value 0 if the function exists, 1 otherwise

fgm
A: 
if declare -F | grep __git_ps1$
then
    PS1=whatever
fi
Jaime Soriano
A: 

I think it is better to use declare, even if it is slightly slower than type. Type suceeds also for aliases or scripts that are in the PATH.

I am using this:

function function_exists
{
    FUNCTION_NAME=$1

    [ -z "$FUNCTION_NAME" ] && return 1

    declare -F "$FUNCTION_NAME" > /dev/null 2>&1

    return $?
}

So later in my scripts I can easily see what's going on:

if function_exists __git_ps1
then
    PS1=__git_ps1
fi

Or even the still readable one-liner:

function_exists __git_ps1 && PS1=__git_ps1
Jacobo de Vera