Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a function definition in Bash?

Tags:

bash

I have defined a few different functions in my .bash_profile. I usually remember the name of function but want to take a quick peek in the code before I run it.

In my .bash_profile I have the following:

gpm () {   echo "git pull origin master"   git pull origin master } 

Now I want to run something like this in Bash:

$ <something> gpm 

Result expected: Don't execute the function just print out the function definition itself.

like image 974
Omar Jalalzada Avatar asked Mar 27 '12 17:03

Omar Jalalzada


People also ask

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.

How does a function return a value in bash?

When a bash function ends its return value is its status: zero for success, non-zero for failure. To return values, you can set a global variable with the result, or use command substitution, or you can pass in the name of a variable to use as the result variable.

How do you define a function in bash?

Defining Bash Functions Functions may be declared in two different formats: The first format starts with the function name, followed by parentheses. This is the preferred and more used format. The second format starts with the reserved word function , followed by the function name.

How do I see bash functions?

We need to use the type command or declare command to find and display bash shell function source code under Linux and Unix.


2 Answers

EDIT: The best answer isn't this one, but the other one below.

What this answer used to say is that you can get a function definition in bash using the type builtin, e.g. type gpm. However, using declare as described in the other answer is better in every way.

like image 94
sorpigal Avatar answered Sep 28 '22 09:09

sorpigal


declare -f gpm will just print the function definition of function gpm with no other text.

like image 23
glenn jackman Avatar answered Sep 28 '22 09:09

glenn jackman