views:

336

answers:

4

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!"
}
+3  A: 

Include in your script the line

source .bashrc

try with the source construct it should work!

Lopoc
it's the if statement that won't behave!(i'm a beast at java, but bash beats the hell out of me)
LES2
+1  A: 
$ source .bashrc
PiedPiper
+1  A: 

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.

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!"
}
Dennis Williamson
+1  A: 

The test in your function won't work - you should not have brackets around the -z clauses, and there should be a space between if and the open bracket. It should read:

function coolness() {

    if [ -z "$1" -o -z "$2" ]; then
        echo "Usage: $0 [sub_package] [endpoint]";
        exit 1;
    fi
    echo "Hi!"
}
Jefromi
this fixed the problem! thanks!
LES2