Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a function exists from a bash script [duplicate]

Tags:

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.

like image 465
csexton Avatar asked Jun 17 '09 14:06

csexton


2 Answers

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 
like image 157
Trevor Robinson Avatar answered Sep 19 '22 14:09

Trevor Robinson


if type __git_ps1 | grep -q '^function$' 2>/dev/null; then     PS1=whatever fi 
like image 40
chaos Avatar answered Sep 17 '22 14:09

chaos