How to properly exit functions in Shell Script?
Is there a proper way to exit a function without returning to previous lines in that function?
For instance, I have a shell script with lots of functions, many of them called from within functions: Code:
functionOne(){ get data from user test data from user if data is incorrect then go to another function called tryAgain Code:
tryAgain(){ Code:
kill $$ Any idea what I'm doing wrong here? Is there a way to terminate the processing of a function? I can post the actual script if needed, but it's really long, so I thought I'd paraphrase here. Thanks a lot in advance for any assistance. |
Use "return". I would also recommend indenting your code - makes it a lot more readable.
For example: Code:
#!/bin/bash Code:
About to call f2 |
Quote:
Thanks a lot for the help. Oh, and yeah I do indent my code - I just didn't in that example because the tab button doesn't work here in the posting window. |
The return value is assigned to $? after the function returns. It should be a positive integer, generally less than 127. 0 indicates success. See the EXIT STATUS section of the bash manual page for more information.
If you don't use a return in a function, the exit status of the last executed command is used instead. For example: Code:
f1 () { Code:
f1 || echo "WARNING, f1 didn't work" |
Quote:
Code:
bash-3.1$ new() if test $1 == 1; then return 0; else return 1; fi |
Excellent. Thank you very much.
|
All times are GMT -5. The time now is 09:17 PM. |