Bash Shell: Check If A Function Exists Or Not (Find Out If a Function Is Defined Or Not)

www.lautt‮u‬ri.com
Bash Shell: Check If A Function Exists Or Not (Find Out If a Function Is Defined Or Not)

To check if a function exists in a Bash shell script, you can use the type command. The type command can be used to display information about a command or function, including whether it is a function or not.

For example, to check if a function named myfunction exists, you can use the following command:

if type "myfunction" | grep -q 'function'; then
  echo "Function myfunction exists"
else
  echo "Function myfunction does not exist"
fi

This will check the output of the type command for the word "function", and if it is present, it will print the message "Function myfunction exists". If the word "function" is not present, it will print the message "Function myfunction does not exist".

Alternatively, you can use the declare builtin command to check if a function is defined. For example:

if declare -f myfunction > /dev/null; then
  echo "Function myfunction is defined"
else
  echo "Function myfunction is not defined"
fi

This will check if the declare command outputs anything when the -f option is used to request information about the function. If the function is defined, it will print the message "Function myfunction is defined", and if it is not defined, it will print the message "Function myfunction is not defined".

Created Time:2017-10-16 14:38:39  Author:lautturi