The UNIX and Linux Forums  


Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #3 (permalink)  
Old 05-05-2008
drl's Avatar
drl drl is offline Forum Advisor  
Registered User
  
 

Join Date: Apr 2007
Location: Saint Paul, MN USA / BSD, CentOS, Debian, OS X, Solaris
Posts: 712
Hi.

It looks like you are using the csh family and you wish to know how to run a command and test the exit status in an if. Most people agree that members of the csh family are not good for scripting because of technical drawbacks and flaws. The Bourne shell family is considered superior for scripting.

However, if you must use csh, you can use braces to obtain the exit status of a command:

Code:
#!/bin/csh

# @(#) s2       Demonstrate csh braces: run command, test exit status.

# Create a scratch file if one does not exist.
touch t1

echo
if ( { ls t1 } ) then
        echo " command ls succeeded."
else
        echo " command ls FAILED."
endif

# Remove file.
rm t1

echo
if ( { ls t1 } ) then
        echo " command ls succeeded."
else
        echo " command ls FAILED."
endif

exit $status

Producing:

Code:
% ./s2

t1
 command ls succeeded.

ls: t1: No such file or directory
 command ls FAILED.

Another method is to run the command outside the if, and set a variable to the exit status variable $status. That is something you can try on your own. See man csh for details -- it's long, but if you continue to use csh, you should know about the features ... cheers, drl