views:

4538

answers:

2

I'm relatively new to Unix shell scripting. Here's my problem. I've used this script...

isql -S$server -D$database -U$userID -P$password << EOF > $test
exec MY_STORED_PROC
go
EOF

echo $test

To generate this result...

Msg 257, Level 16, State 1:
Server 'MY_SERVER', Procedure 'MY_STORED_PROC':
Implicit conversion from datatype 'VARCHAR' to 'NUMERIC' is not allowed.  Use
the CONVERT function to run this query.
(1 row affected)
(return status = 257)

Instead of echoing the isql output, I would like to extract the "257" and stick it in another variable so I can return 257 from the script. I'm thinking some kind of sed or grep command will do this, but I don't really know where to start.

Any suggestions?

+1  A: 

Here is a quick and dirty hack for you, though you should really start learning this stuff yourself:

RC=`tail -1 $test |sed 's/(return status = \([0-9]\+\))/\1/'`
Nikolai N Fetissov
Thanks. That's why I'm asking: I wanted to see experienced Unix coders would solve a real-world problem, so I could learn to do it myself. So in this case, the tail command pipes the last line of $test to the sed command, which returns whatever's inside the \( and )\ (assuming the overall pattern matches). Is that right?
John M Gant
Yes, whatever is between the \( and \) is then given by \1 in the substitution. [0-9]\+ means match one or more digits.
Nikolai N Fetissov
+5  A: 

bash can strip parts from shell variables.

${parameter#pattern} returns the value of $parameter without the part at the beginning that matches pattern.

${parameter%pattern} returns the value of $parameter without the part at the end that matches pattern.

I guess there is a better way to do this, but this should work. So you could combine this into:

% strip the part before the value:
test=${test#Msg }
% strip the part after the value:
test=${test%, Level*}
echo $test

If you're interested in the (return status = xxx) part, it would be:

result=${test#*(result status = }
result=${result%)*}
echo $result

The relevant section of the bash manpage is "Parameter Expansion".

fmarc