4

Learning bash and I was thinking whether this is possible, with case or with some function..

For example..

./test.sh arg1 -p help,contact -e html,php # don't know how to expand them both

OR is it possible to do something like this?

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

I want the output to be like..

URL is www.google.com/help.html

URL is www.google.com/contact.php

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[@]}"; # 
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

4
  • 3
    $ man getopt # one way to go
    – Hannu
    May 18, 2017 at 17:52
  • Can you check the code now? I got so close, but can expand only one with for loop
    – John Doe
    May 18, 2017 at 21:19
  • You are only iterating over extension array, but not over page array. Do you want to combine page names and extensions one to one or one to all? If first - you need for (()) loop with index variable to iterate over both arrays. If second - you need two nested loops
    – andrybak
    May 18, 2017 at 22:52
  • I want to combine one to one (first -p with first -e). So that would be help.html and help.php, then contact.html and contact.php. Can you show how for (()) is done for my script? I'm looking at some examples for "for loops with index variable", will update the post if I make it work. Thanks
    – John Doe
    May 18, 2017 at 23:04

1 Answer 1

1

okay the following seems to work. Thanks to @tso

https://stackoverflow.com/questions/44067504/bash-iterate-multiple-variable-with-for-loop-index

#!/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
1
  • About now you should be able to set this as the answer to your own question, and by that gain some status... :-)
    – Hannu
    May 23, 2017 at 19:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .