Bash - 如何在使用案例切换时扩展变量

Bash - 如何在使用案例切换时扩展变量

学习 bash 时我在思考这是否可行,有案例吗或者有某些功能吗?

例如..

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

或者有可能做这样的事情吗?

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

我想要的输出是这样的......

URL 是 www.google.com/help.html

URL 是 www.google.com/contact.php

代码:

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

输出:# 我能得到的最接近的..第一个 -p 参数

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

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

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

答案1

好的,下面的方法似乎有效。感谢@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

相关内容