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"
Function names and definitions may be listed with the -f option to the declare builtin command (see Bash Builtins). The -F option to declare will list the function names only (and optionally the source file and line number).
A bash function can return a value via its exit status after execution. By default, a function returns the exit code from the last executed command inside the function. It will stop the function execution once it is called. You can use the return builtin command to return an arbitrary number instead.
Typically, when writing bash scripts, we use echo to print to the standard output. echo is a simple command but is limited in its capabilities. To have more control over the formatting of the output, use the printf command. The printf command formats and prints its arguments, similar to the C printf() function.
There are two ways to implement Bash functions: Inside a shell script, where the function definition must be before any calls on the function. Alongside other bash alias commands and directly in the terminal as a command.
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'
You can display the definition of a function in bash using declare. For example:
declare -f foobar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With