How to check whether a function has been defined in Bash?
Posted on In QAI 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
.