Reputation: 2267
How can I write a POSIX shell script that does two things:
1) When $var1 OR $var2 is defined AND non-null, echo "success"
2) When $var3 is defined with anything, echo "success2"
I tried many combinations of the -ne -z and -a operators but I've had no luck.
Upvotes: 0
Views: 70
Reputation: 86333
(I tested the following in a Bash shell in POSIX mode - I am not absolutely certain that all of it is strictly POSIX)
$ var1=
$ var2=
$ if [ -n "$var1" -o -n "$var2" ]; then echo "success"; fi
$ var2=1
$ if [ -n "$var1" -o -n "$var2" ]; then echo "success"; fi
success
$ var3=
$ if [ -n "${var3+X}" ]; then echo "success2"; fi
success2
$ unset var3
$ if [ -n "${var3+X}" ]; then echo "success2"; fi
$
The first condition [ -n "$var1" -o -n "$var2" ]
takes advantage of the fact that the not-null requirement also implies that the variable are set.
The second case is trickier. "${var3+X}"
expands to nothing if var3
is unset and to X
if it is set. That way you can tell unset and null variables apart.
Upvotes: 2