Connecting Tech Pros Worldwide Forums | Help | Site Map

Saving `test` results in a variable

iLL iLL is offline
Member
 
Join Date: Oct 2006
Posts: 62
#1: Nov 30 '06
Is there any way to save the result of a "test" command in a variable, or would I have to do something like:

bool=`if [ -d . ]; then echo 1; else echo 0; fi;`
Moderator
 
Join Date: Nov 2006
Location: Boston, USA
Posts: 505
#2: Dec 2 '06

re: Saving `test` results in a variable


Shell already does it for you.
In Bourne shell the result of the last executed command is saved in variable $?
In C shell it's a built-in variable called status.

Here's the sample script:

Expand|Select|Wrap|Line Numbers
  1. #!/bin/sh
  2. [ -d `pwd` ] 
  3. echo $?
  4. # the statement above should print 0, (success status) 
  5. # because your current directory is obviously a directory.
  6.  
  7. [ -d /dev/nonsence ] 
  8. echo $?
  9. # the statement above will likely to print 1 (failure), 
  10. # it's unlikely that this directory exists
Note that 0 is always a success, but shell may return other failure codes,
so most often you're only interested to see whether you gor 0 or not:

exec some shell command, then test the result:
if [ "$?" -ne 0 ] ; then
... ...

It is a common practice to include $? in double-quotes, as shown above.
Hope it helps.
Reply