Reputation: 639
Recently I come across below code ...
if [ ! $?target -o $target = "" ]; then
echo "Target is not set"
fi
"$taget"
is set or not or "$target"
is empty or not.$?variable
works, but I didn't find any relative search results.Upvotes: 1
Views: 918
Reputation: 205
I put "#!sh" at the top, line 1 and ran it on a Mac OS 10.5.Terminal window, which says its bash...
The original script, with [ ! "$?target" -o "$target" = "" ]' gets try.sh: line 3: [: too many arguments
The version IanNorton suggests works: Target is not set
I get the same results with #!bash on line 1, and no shell specification on line 1.
Your mileage may vary...
Upvotes: -1
Reputation: 7282
I think your script is slightly mis-quoted,
if [ ! "$?target" -o "$target" = "" ]; then
echo "Target is not set"
fi
This will indeed print "Target is not set" when $target is unset, However A much more reliable method for doing this would be:-
if [ "x$foo" = "x" ]; then
echo "foo is not set"
fi
Upvotes: 2
Reputation: 882028
In some shells, csh
for example, $?xyz
will evaluate to 1 if xyz
is set, otherwise it evaluates to 0.
All that snippet is doing is checking if either $target
is not set at all or if it's set to an empty string. In both cases, it assumes it's not set.
Note that this is different from bash
for example where $?
is the return code from the last executed command. In that shell, you'll simply get the return code followed by the variable name, such as 0target
.
Upvotes: 4