user630702
user630702

Reputation: 3097

Bash - iterate multiple variable with for loop index

How to use for (( )) loop with index variable for this script? I can't find any examples to do that..

code:

var1=$1
url="http://www.google.com/"

# maybe use a for loop here??

# Okay now if I use getopts - @Hannu

while getopts ":p:e:" o; do
case "${o}" in
        p)
        page+=("$OPTARG")
        ;;
        e)
        extension+=("$OPTARG")
        ;;
esac
done
shift $((OPTIND -1))

#I need a better for loop here - which can expand both variables

for val in "${extension[@]}"; # how to use for (( )) here?
do

# FAIL - pass first switch arguments -p and -e to for loop

echo "URL is http://www.google.com/$page.$val
done

OUTPUT: # closest I can get to.. first -p argument

./test.sh -p help -p contact -e html -e php

URL is http://www.google.com/help.html

URL is http://www.google.com/help.php

I want the output to be like..

URL is http://www.google.com/help.html

URL is http://www.google.com/contact.php

Upvotes: 1

Views: 522

Answers (1)

tso
tso

Reputation: 4914

voila:

#!/bin/bash
var1=$1
url="http://www.google.com/"

# maybe use a for loop here??

# Okay now if I use getopts - @Hannu

while getopts ":p:e:" o; do
case "${o}" in
        p)
        page+=("$OPTARG")
        ;;
        e)
        extension+=("$OPTARG")
        ;;
esac
done
shift $((OPTIND -1))


for ((i=0;i<${#extension[@]};++i));
do
echo "URL is www.google.com/${page[i]}.${extension[i]}"
done

Upvotes: 1

Related Questions