简体   繁体   English

使用 getopts 参数为空

[英]Argument is empty using getopts

I want to be able to run a script like run.sh test -a but my arguments are empty.我希望能够运行类似run.sh test -a的脚本,但我的 arguments 是空的。

#!/bin/bash

function install() {
    echo "Installing $1"
}

while getopts "ab" ARG; do
  case "$ARG" in
    a) install
       echo "Setting up A" ;;
    b) install
       echo "Setting up B" ;;
    *​) echo "argument missing" ;;
  esac
done

My expected output would be if I run run.sh test -a :如果我运行run.sh test -a ,我预期的 output 将是:

Installing test
Setting up A

However there is no output returned.但是没有返回 output。 If I run run.sh -a , I get:如果我运行run.sh -a ,我得到:

Installing
Setting up A

Probably not the most elegant way but I got it sort of working by using the second argument instead.可能不是最优雅的方式,但我通过使用第二个参数来实现它。

Ended up reworking it like so:最终像这样重新加工它:

install=$2

function install() {
    echo "Installing $install"
}

while getopts "ab" ARG; do
  case "$ARG" in
    a) install
       echo "Setting up A" ;;
    b) install
       echo "Setting up B" ;;
    *​) echo "argument missing" ;;
  esac
done

So I running run.sh -a test would return:所以我运行run.sh -a test会返回:

Installing test
Setting up A

getopts does not allow you to specify the options after the non-option arguments. This is a general principle of many Unix tools, though some have deviated. getopts不允许在非选项arguments 之后指定选项。这是许多Unix 工具的通用原则,尽管有些有所偏离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM