shell脚本传参选项

Example:

 1 opt1=0
 2 opt2=0
 3 set --  `getopt -o a:b: -l opt1:,opt2: -n "$0" -- "$@"`
 4 while [ -n "$1" ]
 5 do
 6     echo "current1: **$1**"
 7     case $1 in
 8         -a|--opt1)
 9                 opt1=$2
10                 shift 2
11                 ;;
12         -b|--opt2)
13                 opt2=$2
14                 shift 2
15                 ;;
16         --) shift; break;;
17          # *) echo "Invalid $1"; exit 1 ;; #no need add this line, getopt will handle invalid option
18     esac
19 done
20 echo "opt1: $opt1"
21 echo "opt2: $opt2"

set -- "$X"讲解: 

set -- "$X"就是把X的值返回给$1, set -- $X就是把X作为一个表达式的值一一返回

    https://blog.csdn.net/fw63602/article/details/52799073

getopt: 每次返回$@的 $1, 参数列表长度减一,常用参数:

#!/bin/bash

 

#定义选项, -o 表示短选项 -a 表示支持长选项的简单模式(以 - 开头) -l 表示长选项 

# a 后没有冒号,表示没有参数

# b 后跟一个冒号,表示有一个必要参数

# c 后跟两个冒号,表示有一个可选参数(可选参数必须紧贴选项)

# -n 出错时的信息

# -- 也是一个选项,比如 要创建一个名字为 -f 的目录,会使用 mkdir -- -f ,

#    在这里用做表示最后一个选项(用以判定 while 的结束)

# $@ 从命令行取出参数列表(不能用用 $* 代替,因为 $* 将所有的参数解释成一个字符串

#                         而 $@ 是一个参数数组)

    

TEMP=`getopt -o ab:c:: -a -l apple,banana:,cherry:: -n "test.sh" -- "$@"`

https://www.jianshu.com/p/d3cd36c97abc

原文地址:https://www.cnblogs.com/i-shu/p/14071980.html