Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can bash show a function's definition?

Tags:

function

bash

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" 
like image 630
k107 Avatar asked Aug 02 '11 18:08

k107


People also ask

How do I see bash functions?

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).

Can bash functions return values?

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.

How do I print a function in bash?

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.

Can you have functions in bash?

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.


2 Answers

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' 
like image 73
Benjamin Bannier Avatar answered Oct 23 '22 12:10

Benjamin Bannier


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

declare -f foobar 
like image 25
pmohandas Avatar answered Oct 23 '22 13:10

pmohandas