Shell 脚本读取命令行参数
1. getoptsgetopts 是 Linux 系统中的一个内置变量一般用在循环中。每当执行循环时getopts都会检查下一个命令选项如果这些选项出现在 option 中则表示是合法选项否则不是合法选项。并将这些合法选项保存在 VARIABLE 这个变量中。1.1. 使用方法getopts [option[:]] [DESCPRITION] VARIABLEoption表示为某个脚本可以使用的选项: 冒号如果某个选项option后面出现了冒号:则表示这个选项后面可以接参数即一段描述信息DESCPRITIONgetopts还包含两个内置变量及OPTARG和OPTINDOPTARG 就是将选项后面的参数或者描述信息DESCPRITION保存在此变量当中。OPTIND 这个表示命令行的下一个选项或参数的索引文件名不算选项或参数while getopts :a:bc: opt第一个冒号表示忽略错误字符后面的冒号表示该选项必须有自己的参数。$OPTARG 存储相应选项的参数如下例中的11、5$OPTIND 总是存储原始$*中下一个要处理的选项不是参数而是选项此处指的是a, b, c这三个选项而不是那些数字当然数字也是会占有位置的位置。1.2. 使用示例#!/bin/bash echo $* while getopts :a:bc: opt do case $opt in a) echo $OPTARG $OPTIND;; b) echo b $OPTIND;; c) echo c $OPTIND;; ?) echo error exit 1;; esac done2. getopt#/bin/bash ################################### # Extract command line options values with getopt # set -- $(getopt -q ab:cd $) # echo while [ -n $1 ] do case $1 in -a) echo Found the -a option ;; -b) param$2 echo Found the -b option, with parameter value $param shift ;; -c) echo Found the -c option ;; --) shift break ;; *) echo $1 is not option;; esac shift done # count1 for param in $ do echo Parameter #$count: $param count$[ $count 1 ] done #3. 普通方法# main function while [ -n $1 ] do case $1 in --feature_extractor) feature_extractor $2 exit ;; --exhaustive_matcher) exhaustive_matcher $2 exit ;; --gui) gui exit ;; --help) help exit ;; esac done参考文献shell的getopts命令 - 迷你淘 - 博客园Shell中使用getopt、getopts命令_ 静静是我女朋友-CSDN博客