I understand what the exit status of a command is, but I am unclear on how to test for it. A brief example is all I really need.
Thanks.
This is just an example of some logic:
ps -ef | grep sendmail | grep -v grep;
if [ $? .eq 1 ] then "restart sendmail;
if [ $? .eq 0 ] then exit;
In the fragment above, the script checks for a running sendmail process. If it returns 'something' (in this case a match on sendmail) the return code is 0. If it returns nothing (no match, process not running) it returns 1. This is how I used to use return codes in shell scripts (similar in C programs, etc.)
Thanks Neo (as always). One more question. What does the $? signify?
$? is the built-in shell variable that holds the exit code of the last command executed in the shell. I think it is used in many shells, but I am not sure which ones exactly. I've used it in KSH and SH (as I recall, but I don't work in Bourne shell, mostly KSH). I do recall $? used to hold the exit code of the last command in the Bourne shell from a 10 year ago past project. Maybe after coffee the neurons with fire from this memory bank
Hope this helps clarify.
Hi,
I am using CSH and trying to get a similar thing as follows.
I am not getting where I go wrong. could anyone please guide me?
#!/usr/bin/csh
set a = `grep "primary \# secondary" ar128.log`
if($a == 0) then
sed 's/primary \# secondary/secondary \#primary \#secondary/' ar128.log > ar128.log.ext
else
sed 's/secondary \#primary \#secondary/primary \# secondary/' ar128.log > ar128.log.ext
endif
i get no error even...
thanks
sskb
A command like:
grep string < file
finds the lines that match string in file. You are setting your "a" variable to all those lines. And the result of the grep will never be a "0" since the string you are searching for is not "0". If nothing matches the string, grep doesn't print a 0. It prints nothing at all. In that case the "a" variable is empty and still won't match "0".
Try piping the grep to "wc -l" so that you set "a" to a count of the lines.
Hi Perderabo,
I was actually trying to get the return value from the grep.
through man grep I found that the return values for grep are like this
0 One or more matches found.
1 No match found.
2 Syntax error or inaccessible file
\(even if matches were found\).
but while I wanted to print $a it worked as u said. In this case, how can i get these return values ? and If I get that do you think my script would work?
Regards,
sskb
In csh, the return code is in $status. I guess you could just run grep and send the output to /dev/null and then test $status.
Whether your script will work or not depends on whether you write it correctly.