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 function normally defined in git-completion.bash
which comes with git source, or by one of the bash completion scripts that ports/apt installs.
I realize this is an old question, but none of the other answers do this quite as simply as I'd like. This uses type -t
(as suggested in a comment by Chen Levy) as an efficient type-of test, but then uses shell string comparison rather than invoking grep.
if [ "$(type -t somefunc)" = 'function' ]; then somefunc arg1 arg2 fi
And to take it a step further, it also works indirectly:
funcname=do_it_special_$somehow if [ "$(type -t $funcname)" != 'function' ]; then funcname=do_it_normal fi $funcname arg1 arg2
if type __git_ps1 | grep -q '^function$' 2>/dev/null; then PS1=whatever fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With