Can bash show a function's definition?

BashFunction

Bash Problem Overview


Is there a way to view a bash function's definition in bash?

For example, say I defined the function foobar

function foobar {
    echo "I'm foobar"
}

Is there any way to later get the code that foobar runs?

$ # non-working pseudocode
$ echo $foobar
echo "I'm foobar"

Bash Solutions


Solution 1 - Bash

Use type. If foobar is e.g. defined in your ~/.profile:

$ type foobar
foobar is a function
foobar {
    echo "I'm foobar"
}

This does find out what foobar was, and if it was defined as a function it calls declare -f as explained by pmohandras.

To print out just the body of the function (i.e. the code) use sed:

type foobar | sed '1,3d;$d'

Solution 2 - Bash

You can display the definition of a function in bash using declare. For example:

declare -f foobar

Solution 3 - Bash

set | sed -n '/^foobar ()/,/^}/p'

This basically prints the lines from your set command starting with the function name foobar () and ending with }

Solution 4 - Bash

set | grep -A999 '^foobar ()' | grep -m1 -B999 '^}'

with foobar being the function name.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionk107View Question on Stackoverflow
Solution 1 - BashBenjamin BannierView Answer on Stackoverflow
Solution 2 - BashpmohandasView Answer on Stackoverflow
Solution 3 - BashJurgen van der MarkView Answer on Stackoverflow
Solution 4 - BashpyroscopeView Answer on Stackoverflow