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

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

asked Apr 18, 2016 by anonymous

1 Answer

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.

answered Apr 25, 2016 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...