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!" }
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.
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.
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.
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.
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