Bash - 使用for循环索引迭代多个变量

时间:2017-05-19 10:21:08

标签: bash shell

如何将(())循环用于此脚本的索引变量?我找不到任何这样的例子..

代码:

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

输出:#extour我可以到达..第一个-p参数

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

网址为http://www.google.com/help.html

网址为http://www.google.com/help.php

我希望输出像..

网址为http://www.google.com/help.html

网址为http://www.google.com/contact.php

1 个答案:

答案 0 :(得分:1)

瞧瞧:

#!/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