rcwizard12435 rcwizard12435 - 3 years ago 67
Bash Question

How can I take lines from a text file as an argument using a loop

If I have a text file called inventory.txt that looks like this:

america
mexico
england


If I run this code, it only runs through once for
america


while read line;
do
while getopts "U:D:" opt;
do
case $opt in
U)
SOURCE=$OPTARG
echo "SOURCE : $SOURCE"
SITEID=$line
echo "SITE : $SITEID " >&2
;;

D)
DEST=$OPTARG
echo "DESTINATION : $DEST" >&2
;;
esac

done

done < inventory.txt


How can I do this for all the lines in my text file?

Answer Source

Parse the parameters first, then afterwards go through your file:

while getopts "U:D:" opt;
do
    case $opt in
        U)
            SOURCE=$OPTARG
            ;;

        D)
            DEST=$OPTARG
            ;; 
    esac
done


while read line;
do 
    echo "SOURCE : $SOURCE"     
    SITEID=$line
    echo "SITE : $SITEID " >&2
    echo "DESTINATION : $DEST" >&2  
done < inventory.txt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download