Reputation: 21425
I am trying to invoke a function from command prompt, but I am not finding the correct way to invoke it.
This is my script:
echo "Hello World!"
test {
echo "Sample message"
}
I tried below ways:
sh-4.2$ main.sh test
Hello World!
./main.sh: line 5: usuage: command not found
A helpful message!
./main.sh: line 8: syntax error near unexpected token `}'
./main.sh: line 8: `}'
sh-4.2$ . main.sh test
Hello World!
sh: usuage: command not found
A helpful message!
sh: ./main.sh: line 8: syntax error near unexpected token `}'
sh: ./main.sh: line 8: `}'
sh-4.2$ . main.sh test()
sh: syntax error near unexpected token `('
Can you please help me in this.
Upvotes: 0
Views: 42
Reputation: 85800
Couple of issues here, the syntax for test
function is wrong, you need have the parentheses around,
test() {
echo "Sample message"
}
export -f test
The export -f
syntax allows you to export your functions to the shell; to run them from the command-line you need to source the script in the current shell as,
$ . ./main.sh
Hello World!
Now you can call the function test
directly from the command line after having exported it from the script,
$ test
Sample message
Also a good practice to NOT have functions name test
, because it is same name a shell
built-in. Recommend using some custom names for that.
Upvotes: 2