-   Programming (
-   -   do while loop, but all at once? (

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

<login to router and do stuff>

done < devices.txt

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


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?


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

while read device dummy ; do
        # Login to "$device", do the work
    ) &
done < devices.txt

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

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
while read device dummy ; do
    if [ -e "$WORK/${device//\//_}.ok" ]; then
        echo "$device: Success" >&2
        echo "$device: Failure" >&2
    cat "$WORK/${device//\//_}.log"
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 08:02 PM.