Bhavik
Bhavik

Reputation: 639

$?<variable> in sh


Recently I come across below code ...


if [ ! $?target -o $target = "" ]; then
    echo "Target is not set"
fi

I am curious to understand logic of above code snippet.
It seems that it is checking, if I am correct, whether "$taget" is set or not or "$target" is empty or not.

I google to find how $?variable works, but I didn't find any relative search results.

So please help me to understand how it works. Thanks in advance.

Upvotes: 1

Views: 918

Answers (3)

Bill IV
Bill IV

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

IanNorton
IanNorton

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

paxdiablo
paxdiablo

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

Related Questions