How to check whether a function has been defined in Bash?

Posted on In QA

I would like to know whether a function, say f1(), has already been defined in Bash. How should I do it?

You can use the type -t to get a string of the type of the name:

If the -t option is used, type prints a string which is one of alias, keyword, function, builtin, or file if name is an alias, shell reserved word, function, builtin, or disk file, respectively.

So this piece of code check whether a function has already been defined:

tf=$(type -t f1 2>/dev/null || rt=$?)
if [[ "$tf" != "function" ]]; then
    echo "f1 is defined as a function"
fi

The rt=$? here makes sure that statement’s return code is 0 so that it works well with set -o errexit.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *