LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   do while loop, but all at once? (http://www.linuxquestions.org/questions/programming-9/do-while-loop-but-all-at-once-861943/)

russell3901 02-10-2011 09:32 PM

do while loop, but all at once?
 
Hi All,

Currently I run do-while loops to login to a number of devices.

like so;

--------------------
while read line
do

<login to router and do stuff>

done < devices.txt
--------------------

I have my device list in devices.txt in the following format;

device1
device2
device3
device4
etc.

While this works very well, its time consuming with alot of devices.
Is there a way to run though the device list concurrently (via do while or another method) so it hits them all at the same time?

Thanks,

Nominal Animal 02-10-2011 10:53 PM

Yes. If you don't need the output (or don't mind any output being a mashup of all), and don't care about their exit statuses, you can just do
Code:

#!/bin/bash
while read device dummy ; do
    (
        # Login to "$device", do the work
    ) &
done < devices.txt
wait

If you need the conversation log from each device, you can do eg.
Code:

#!/bin/bash
WORK="`mktemp -d`" || exit $?
trap "rm -rf '$WORK'" EXIT
while read device dummy ; do
    ( exec &>"$WORK/${device//\//_}.log"

      # Do the login stuff.
      # Use 'exit' to quit early, if problems occur.

      # Only do this if success.
      touch "$WORK/${device//\//_}.ok"
    ) &
done < devices.txt
wait
while read device dummy ; do
    if [ -e "$WORK/${device//\//_}.ok" ]; then
        echo "$device: Success" >&2
    else
        echo "$device: Failure" >&2
    fi
    cat "$WORK/${device//\//_}.log"
    echo
done < devices.txt

Note that you can add further files into $WORK (for example, describing errors if any), and not worry about them being cleaned up, because the trap will always remove it and its contents automatically when the script exits, no matter the reason.
The script will also exit with failure (nonzero status) if any of the device logins failed.

Does this work for you, or do you also need interactive input for the login processes?
Nominal Animal


All times are GMT -5. The time now is 02:02 AM.