Bash: Print usage statement & exit; otherwise continue using Bash shorthand operators
I'm trying to write a Bash script using some shorthand Bash operators.
I want a short script to test for a commandline argument. - If $1 is not present, then print a Usage statement and exit from the function. - If there is a value, then continue with the rest of the function. Code:
function testIt { Code:
$ testIt Any help is appreciated. -= Stefan |
Try this:
Code:
#!/bin/sh |
I think the reason you were still getting the "FOO=" output is that ( echo "Usage: testIt foo"; exit 0 ; ) runs in a subshell because of the brackets. It exits from the subshell at your exit statement and continues with the script. dogpatch's example executes in one level...
|
Thanks Dogpatch. The 'if ; then; fi' certainly works.
I was just trying to figure out how to do this with the shorthand operators like [[ TEST ]] || and && . Since I write these sorts of scripts often, I was hoping to find a one-liner to do this. Plus, it'd slick. It *should* work at some level, right? Hrm, I'll have to work on this more. |
Here is one way to do it:
Code:
.. |
[[ -n "$1" ]] && echo "FOO=$1" || echo "Usage: testIt foo"
|
Quote:
|
Quote:
However, if I put this in function within my current interactive shell, my current shell will exit. I'm not saying that your solution is wrong ;) It is just an interesting thing to notice. |
Quote:
Code:
.. |
Thank you jlliagre. Both of your solutions work.
Thanks! |
All times are GMT -5. The time now is 09:33 PM. |