Friday BASH Script question - Check output during for loop
Hey folks,
It's been a long friday and was a late night last night so I'm pretty sure I'm just not thinking about this correctly but basically what I would like to do is check for a set of output while doing a for loop, break out of the loop if it contains a certain string of text. So lets say I have a list of duplicates in a file /tmp/dupes.txt Format: Code:
client1 Code:
Code:
Is this easily achievable with my for loop setup or would I need to look at re-writing this a bit more robustly. Tried to nest an if statement in the for loop but wasnt able to get it to work. |
Well I just went the lazy way here, logged all output to another tmp file, then do a grep on that for enabled. Not the most efficient but gets the job done. Will leave "unsolved" for a little while longer incase anyone has suggestions.
|
Something like (not tested)
Code:
for dupe in $(/bin/cat /tmp/dupes.txt) Code:
regex='scheduled backup: Enabled' |
You could throw an if statement in there to accomplish what you're looking for. While this isn't the most robust way of doing it, it should work:
Code:
for dupe in $(/bin/cat /tmp/dupes.txt); do |
Please, don't ever use for loops with command substitutions, and especially not with cat.
Always use a while+read loop with text file or data stream input. Otherwise, it's pretty much what Catkin said before. Code:
#!/bin/bash Another option, when you are in bash, is to use the mapfile built-in to populate an array with line entries. then you can safely use a for loop. Code:
#!/bin/bash |
David, in all my time with BASH nobody has ever mentioned the for loop reading gotchas that you have on that wiki post. Thank you for that especially. I re-scripted it today and it is a more scalable solution by far. Thanks to everyone for their input, my half-a$$ed script from last week is pretty sloppy.
|
Glad to have helped out.
Yes, there's a lot of poor coding advice going around. While I've been scripting for almost 10 years now, it wasn't until I discovered the wooledge site a few years ago that I really learned what constitutes good and bad use of its features. I highly suggest reading through the BashGuide, BashFAQ, and BashPitfalls pages. It should help your coding immensely. BTW, I notice I made a scripting mistake, capturing the query to the variable $output, but stupidly using the variable $text in the follow-up test. I'm updating the above to fix that. |
All times are GMT -5. The time now is 07:25 PM. |