getopts 在 bash 脚本中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18115885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:11:07  来源:igfitidea点击:

getopts not working in bash script

bashunix

提问by vkaul11

#! bin/bash
# code for train.sh
   while getopts "f:" flag
    do
         case $flag in 
             f)
               echo "Hi" 
               STARTPOINT = $OPTARG
               ;;
         esac
    done

    echo Test range: 
    echo Train range: 

    #path of experiment folder and data folder:
    EXP_DIR=""
    DATA_DIR=""
    echo Experiment: $EXP_DIR
    echo DataSet: $DATA_DIR
    echo file: $STARTPOINT


I ran the command > ./train.sh test1  test2 test3 test4  -f testf  

and got the output

并得到输出

Test range: test4
Train range: test3
Experiment: test1
DataSet: test2
file:

So getopts option does not seem to work for some reason as you can see the nothing is printed after file and also echo "Hi" command is not executed in the case statement. Can anyone please help me with this?

因此 getopts 选项由于某种原因似乎不起作用,因为您可以看到文件后没有打印任何内容,并且在 case 语句中未执行 echo "Hi" 命令。任何人都可以帮我解决这个问题吗?

回答by KeepCalmAndCarryOn

You need to put any options before naked parameters

您需要在裸参数之前放置任何选项

./train.sh -f testf test1  test2 test3 test4

with output

带输出

Hi
Test range: test4
Train range: test3
Experiment: test1
DataSet: test2
file: testf

You need a couple of changes too

你也需要一些改变

while getopts "f:" flag
do
     case $flag in
         f)
           echo "Hi" 
           STARTPOINT=$OPTARG
           shift
           ;;
     esac
     shift
done

To set the environment variable and shift the got option out of the way

设置环境变量并将 got 选项移开

回答by aks

Two points:

两点:

  1. the options parsing must occur before non-options parsing.
  2. the shift to remove the options can occur once, after all options have been parse.
  1. 选项解析必须发生在非选项解析之前。
  2. 在所有选项都被解析之后,移除选项的转变可以发生一次。

Used on a while, the getoptsfunction does not need a shift within the loop. However, after the while getoptscompletes, a shift isneeded in order to process the non-option arguments. The variable OPTINDindicates the index of the next non-option to be parsed, and this value can be used in a shiftcommand.

用于 a while,该getopts函数不需要循环内的移位。然而,后while getopts完成,换档需要的,以便处理非选项参数。该变量OPTIND表示下一个要解析的非选项的索引,该值可以在shift命令中使用。

Here is an example, where I also include the h, nand voptions for "help", "norun" and "verbose" flags:

这是一个示例,其中我还包括“帮助”、“norun”和“详细”标志的h,nv选项:

while getopts 'f:hnv' opt ; do
  case "$opt" in 
  h) usage ;; 
  n) norun=1 ;; 
  f) echo "Hi" ; STARTPOINT="$OPTARG" ;; 
  v) verbose=1 ;; 
  esac 
done 
shift $(( OPTIND - 1 ))