Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a function defined in .bashrc from the shell?

In my .bashrc, I have a function called hello:

function hello() {    echo "Hello, $1!" } 

I want to be able to invoke hello() from the shell as follows:

$ hello Lloyd 

And get the output:

> Hello, Lloyd! 

What's the trick?

(The real function I have in mind is more complicated, of course.)

EDIT: This is REALLY caused by a syntax error in the function, I think! :(

function coolness() {      if[ [-z "$1"] -o [-z "$2"] ]; then         echo "Usage: $0 [sub_package] [endpoint]";         exit 1;     fi         echo "Hi!" } 
like image 718
les2 Avatar asked Sep 30 '09 20:09

les2


People also ask

How do you call a function in bash shell?

To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.

How do you call a function in shell script?

The name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.

How do you write and call a function in bash?

Creating a Function in Bash The code between the curly braces {} is the function body and scope. When calling a function, we just use the function name from anywhere in the bash script. The function must be defined before it can be used.


1 Answers

You can export functions. In your ~/.bashrc file after you define the function, add export -f functionname.

function hello() {    echo "Hello, $1!" }  export -f hello 

Then the function will be available at the shell prompt and also in other scripts that you call from there.

Note that it's not necessary to export functions unless they are going to be used in child processes (the "also" in the previous sentence). Usually, even then, it's better to source the function into the file in which it will be used.

Edit:

Brackets in Bash conditional statements are not brackets, they're commands. They have to have spaces around them. If you want to group conditions, use parentheses. Here's your function:

function coolness() {      if [ -z "$1" -o -z "$2" ]; then         echo "Usage: $0 [sub_package] [endpoint]";         exit 1;     fi         echo "Hi!" } 

A better way to write that conditional is:

    if [[ -z "$1" || -z "$2" ]]; then 

because the double brackets provide more capability than the single ones.

like image 125
Dennis Williamson Avatar answered Sep 23 '22 06:09

Dennis Williamson