euglug.org

[Eug-lug] Reading data to multiple variables

작성자

카테고리:



Neil ParkerWed Jul 28 22:36:34 PDT 2004

Some more suggestions, which didn't occur to me until it was too late to
incorporate them into my previous message...

Garl Grigsby wrote,
>for unit in /proc/scsi/usb-storage-*/*
>    do
>      cat $unit > /tmp/unit
>      while read name value
>      do
>           case "$name" in
>               GUID:)       guid="$value";;
>               Attached:)   attached="$value";;
>           esac
>      done < /tmp/unit
>      echo ${unit}: GUID: $guid attached: $attached
>      # do something useful for one unit here.
>    done

To make it slightly more bulletproof, try this:

     temp=/tmp/unit$$
     trap 'rm -f $temp;exit 0' 1 2 3 15
     for unit in /proc/scsi/usb-storage-*/*
     do cat $unit>$temp
        while read name value
        do case "$name" in
           GUID:) guid="$value";;
           Attached:) attached="$value";;
           esac
        done<$temp
        echo ${unit}: GUID: $guid attached: $attached
        # do something useful for one unit here.
     done
     rm $temp

Putting "$$" in the temporary filename protects against two or more
copies of your script running at the same time--that way they each get
unique temporary filenames, and won't confuse each other by overwriting
each other's temporary data.

The trap command makes sure that the temporary file gets cleaned up even
if you kill the script before it finishes.  Putting "-f" on the rm command
line makes rm shut up, so that if you kill the script after the "trap" but
before the first "cat $unit>$temp", it won't complain about missing files.

              - Neil Parker