Error codes in a for loop
I've got a 'nested' for loop which has a grep in it, if the grep fails there's no output - however the error code is still $0 and the second for loop is still entered, there's also a grep in the second for loop.
I guess ultimately what i need to know is whether there's a way of making grep generate an error code. when no results are found? |
You'll probably have to show a script segment. If you just do a grep on the command line and then immediately echo $?, you will see that it returns a code. You need to capture that code in your script before anything else is done that changes $?.
|
Hi,
from the manpage: Quote:
|
Yeah - that does seem accurate actually (works on my tests). I have two subsequent greps though, perhaps this is effecting the code :S
Code:
xe vm-list | grep -A1 NOTREAL | grep power | awk '{print $5}' |
Quote:
|
Oh, suddenly it's clicking! Thanks :D Will google a bit before I ask my next obvious question :S
|
Try also including PIPESTATUS in your google search.
|
OK, managed to handle this with perl - however it doesn't work with my for loops now :(
|
Gonna need some help with this, will post 'similar' code tomorrow but basically my oneliner enters a for loop which grabs a uuid (have some perl to echo a none zero exit code if theres no match) this uuid is then used in another for loop (again using perl for the none zero exit code thing) to list virtual server snapshots (specificall the snapshot uuid). This then reverts to a specified snapshot - essentially it's a one liner to rewind xen snapshots, but if insert incorrect info in either of my for loops the exit code is always zero - if I run the code outside the for loop the exit code is always nonezero. Hard to explain without an example... This is psuedocode, expect something which actually works tomorrow at some point:
Code:
for uuid in `list virtual servers | grep 'correct-server' | perl -alne '{ print $F[4] } END { exit($.==0) }'`; |
Code:
|
Quote:
Something like: Code:
if xe vm-list | grep -A1 NOTREAL > scratch; then |
Quote:
|
crts gave good advice in post 7
|
Quote:
The issue is the loop, the loop continues to function if the exit status is 1 :( Code:
[root@localhost ~]# xe vm-list | grep -B1 WRONGVMNAME | grep uuid | perl -alne '{ print $F[4] } END { exit($.==0) }' |
Code:
$ help for Code:
status=1 |
All times are GMT -5. The time now is 04:57 PM. |