Find bash function
Published on Mar 04, 2014 by Sachin.
In this post I’ll walk you through few commands which will help to find the location & definition of Bash functions.
I have lot of custom Bash functions for every seldom and frequent
tasks. Usually I like to store these functions in ~/.bashrc
file but
when they grow in size and importance, I like to keep it in a separate
Bash script and source
this script from ~/.bashrc
. As these Bash
scripts goes on increasing and so does the functions, it becomes
tedious to locate these functions.
Unlike which
command, which is used to find a program file location,
we can’t use it to find Bash function location. But there is a way we
can read the function definition and also find its location.
Read function definition
type
can be used to read function definition.
type -a <FUNCTION-NAME>
For example, I have a function called mcd
to create new directory
and cd
in to it. The following command will print the function
definition
type -a mcd
Output:
1: # mcd is a function 2: mcd () { 3: if [ "$#" -eq 1 ]; then 4: mkdir --parents "$1"; 5: cd "$1"; 6: else 7: echo "Usage: mcd <DIR_NAME>" > /dev/stderr; 8: fi 9: }
Update (2016-04-06 Wed)
If you enable shell debug ON USING set -e
, you can still read a function
definition.
1: set -e 2: which mcd
Find function location in a file
In the similar way declare
can be used to locate the function.
To locate the function, turn on shell debugging using
shopt -s extdebug
and then
declare -F <FUNCTION-NAME>
For example, to find mcd
’s location, type
declare -F mcd
Output:
mcd 51 /home/sachin/.bashrc
51 is the line number in file ~/.bashrc
where mcd
is defined.
Finally turn off shell debugging.
shopt -u extdebug
Custom function
Its better to write a custom function(whichf
in this case) using
above commands.
1: function whichf () { 2: if [ ${1} ]; then 3: shopt -s extdebug 4: declare -F ${1} 5: shopt -u extdebug 6: type -a ${1} 7: else 8: echo "Error: Expected Function name as an argument!" 9: fi 10: }
Copy above function in ~/.bashrc
file and source the file using
source ~/.bashrc
Now call this function by typing
whichf <FUNCTION-NAME>
For example
whichf mcd