356

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"
k107
  • 15,882
  • 11
  • 61
  • 59

4 Answers4

468

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'
Coder Guy
  • 1,843
  • 1
  • 15
  • 21
Benjamin Bannier
  • 55,163
  • 11
  • 60
  • 80
313

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

declare -f foobar
pmohandas
  • 3,669
  • 2
  • 23
  • 25
8
set | sed -n '/^foobar ()/,/^}/p'

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

  • 2
    I'm positively surprised that the `set` output has a) comments stripped out, and b) normalized the white space between function name and parens. I'm still reluctant to use this as there may be variables that contain `}` that may trip the simple parsing. – Robert Jan 05 '21 at 19:12
4
set | grep -A999 '^foobar ()' | grep -m1 -B999 '^}'

with foobar being the function name.

pyroscope
  • 4,120
  • 1
  • 18
  • 13
  • 4
    problem: will only display up to the first "}", which is not everything whenever the defintion contains nestings of "{...}" which indeed Bash does allow. – Destiny Architect Jul 21 '14 at 02:45
  • 1
    Can also fail if the function contains a here-doc/here-string containing the curly-brace pattern – Cheetah Sep 28 '15 at 16:49