Shell脚本:虽然循环过早退出

时间:2016-02-22 15:02:00

标签: bash shell

我有一个bash脚本来重新签名.ipa文件。你可以用:

运行它
./mrs.sh -i eliterature.ipa -d "eliterature 123" -v 3.8.0.0 -s 3.8.0 -b com.company.eliterature.123

在开头有一个while循环,它检查所有给定的选项:

echo "Signing with following options: "

while getopts "h?i:b:t:p:v:s:d:x" opt; do
    case "$opt" in
    h|\?)
        show_help
        exit 0
        ;;
    i)  echo "  - Ipa Path: ${OPTARG}"
        ipa_path=$OPTARG
        ;;
    b)  echo "  - Bundle ID: ${OPTARG}"
        CFBundleIdentifier_new=$OPTARG
        ;;
    t)  echo "  - Team ID: ${OPTARG}"
        teamid_new=$OPTARG
        ;;
    p)  echo "  - Provisioning Profile: ${OPTARG}"
        provisioning_profile=$OPTARG
        ;;
    v)  echo "  - CFBundleVersion: ${OPTARG}"
        CFBundleVersion_new=$OPTARG
        ;;
    s)  echo "  - CFBundleShortVersionString: ${OPTARG}"
        CFBundleShortVersionString_new=$OPTARG
        ;;
    d)  echo "  - Display Name: ${OPTARG}"
        CFBundleDisplayName_new=$OPTARG
        ;;
    esac
done

shift $((OPTIND-1))

问题始终是最后一个被忽略的选项。如果while循环声明如下:

while getopts "h?i:b:t:p:v:s:d" opt; do

忽略-d选项。如果我在声明中添加一个额外的字母,则执行-d选项:

while getopts "h?i:b:t:p:v:s:d:x" opt; do

如何在不添加任何额外未使用字母的情况下使while循环正常工作?

1 个答案:

答案 0 :(得分:4)

您需要在:之后添加冒号d,这是在命令行-d之后传递参数所必需的。

根据man 1 getopt

  

如果字母后跟冒号,        期望该期权有一个参数可能会或可能不会被空格分隔

工作代码:

echo "Signing with following options: "

while getopts "h?i:b:t:p:v:s:d:" opt; do
    case "$opt" in
    h|\?)
        show_help
        exit 0
        ;;
    i)  echo "  - Ipa Path: ${OPTARG}"
        ipa_path=$OPTARG
        ;;
    b)  echo "  - Bundle ID: ${OPTARG}"
        CFBundleIdentifier_new=$OPTARG
        ;;
    t)  echo "  - Team ID: ${OPTARG}"
        teamid_new=$OPTARG
        ;;
    p)  echo "  - Provisioning Profile: ${OPTARG}"
        provisioning_profile=$OPTARG
        ;;
    v)  echo "  - CFBundleVersion: ${OPTARG}"
        CFBundleVersion_new=$OPTARG
        ;;
    s)  echo "  - CFBundleShortVersionString: ${OPTARG}"
        CFBundleShortVersionString_new=$OPTARG
        ;;
    d)  echo "  - Display Name: ${OPTARG}"
        CFBundleDisplayName_new=$OPTARG
        ;;
    esac
done

shift $((OPTIND-1))