Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to access return value of unix command. 1

Status
Not open for further replies.

Awkunix

Programmer
Apr 8, 2003
3
0
0
US
Hi,

How can we get the return value of any unix command. For ex. The wc command gives return value of 0 if its successful else it gives > 0 for error occurred.

Can I assign this return value to shell variable ? or can I use this return value directly in “if [ condition ] “

Thanks for the help.

VK
 
[tt]if wc ...; then
echo "wc worked"
else
echo "wc failed"
fi[/tt]
works and the return value is also stored in [tt]$?[/tt]

//Daniel
 
$? is the last return code encountered. Be careful almost everything provides a return code so
grep -q "file" *
ls -la
echo $? # returns zero regardless of grep, because ls was successful.
grep -q "file" *
RC=$? #save the return code to check later
ls -la

To test the return code
cp filea fileb
if [ $? -ne 0 ]
then
echo "copy failed"
else
echo "copy successful"
fi
While many systems prevent assignment of a value to $?, you can provide your own return code.

cp filea fileb
if [ $? -ne 0 ]
then
echo "copy failed"
RC=0
else
echo "copy successful"
RC=1
fi
exit $RC
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top