1

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

awesome! Thank you
Can you explain that line? " i<${#extension[@]} ".How did it work.. i=0; and then i is less than #value? What is it called? So I can search myself :)
${#arrayname[@]} gives you the length of the array. :))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.