shell脚本传可选参数 getopts 和 getopt的方法

本文详细介绍了Shell脚本中参数的传递与解析方法,包括基本的getopts用法及如何处理可选参数,通过示例代码展示了不同参数配置下脚本的运行效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写了一个shell脚本,需要向shell脚本中传参数供脚本使用,达到的效果是传的参数可以是可选参数

下面是一个常规化的shell脚本:

        echo "执行的文件名为: $0";
        echo "第一个参数名为: $1";
        echo "第二个参数名为: $2"

正常的向shell脚本中传参数的方法为:

             ./test.sh 1 2 3

最后执行的结果为:

 

        执行的文件名为: ./test.sh
        第一个参数名为: 1
        第二个参数名为: 2

但是这个是只能按照顺序传递参数,并且不能传递可选参数,然后查资料,发现了一个shell的getopts 用法

 首先贴个例子

[hello@Git shell]$ bash test.sh -a hello
this is -a the arg is ! hello
[hello@Git shell]$ more test.sh 
#!/bin/bash
 
while getopts "a:" opt; do
  case $opt in
    a)
      echo "this is -a the arg is ! $OPTARG" 
      ;;
    \?)
      echo "Invalid option: -$OPTARG" 
      ;;
  esac
done

getopts一共有两个参数,第一个是-a这样的选项,第二个参数是 hello这样的参数。

选项之间可以通过冒号:进行分隔,也可以直接相连接,:表示选项后面必须带有参数,如果没有可以不加实际值进行传递

例如:getopts ahfvc: option表明选项a、h、f、v可以不加实际值进行传递,而选项c必须取值。使用选项取值时,必须使用变量OPTARG保存该值。

[hello@Git shell]$ bash test.sh -a hello -b
this is -a the arg is ! hello
test.sh: option requires an argument -- b
Invalid option: -
[hello@Git shell]$ bash test.sh -a hello -b hello -c 
this is -a the arg is ! hello
this is -b the arg is ! hello
this is -c the arg is ! 
[hello@Git shell]$ more test.sh 
#!/bin/bash
 
while getopts "a:b:cdef" opt; do
  case $opt in
    a)
      echo "this is -a the arg is ! $OPTARG" 
      ;;
    b)
      echo "this is -b the arg is ! $OPTARG" 
      ;;
    c)
      echo "this is -c the arg is ! $OPTARG" 
      ;;
    \?)
      echo "Invalid option: -$OPTARG" 
      ;;
  esac
done
[hello@Git shell]$ 

执行结果结合代码显而易见。同样你也会看到有些代码在a的前面也会有冒号,比如下面的

情况一,没有冒号:

[hello@Git shell]$ bash test.sh -a hello
this is -a the arg is ! hello
[hello@Git shell]$ bash test.sh -a
test.sh: option requires an argument -- a
Invalid option: -
[hello@Git shell]$ more test.sh 
#!/bin/bash
 
while getopts "a:" opt; do
  case $opt in
    a)
      echo "this is -a the arg is ! $OPTARG" 
      ;;
    \?)
      echo "Invalid option: -$OPTARG" 
      ;;
  esac
done
[hello@Git shell]$ 

情况二,有冒号:

[hello@Git shell]$ bash test.sh -a hello
this is -a the arg is ! hello
[hello@Git shell]$ bash test.sh -a 
[hello@Git shell]$ more test.sh 
#!/bin/bash
 
while getopts ":a:" opt; do
  case $opt in
    a)
      echo "this is -a the arg is ! $OPTARG" 
      ;;
    \?)
      echo "Invalid option: -$OPTARG" 
      ;;
  esac
done

情况一输入 -a 但是后面没有参数的的时候,会报错误,但是如果像情况二那样就不会报错误了,会被忽略。

while getopts ":a:bc" opt  #第一个冒号表示忽略错误;字符后面的冒号表示该选项必须有自己的参数 

参考 https://blog.youkuaiyun.com/xluren/article/details/17489667

但是这样还是无法满足可以输入可选参数的要求,这样输入的参数名称也是固定的,参数的数量也是固定的,然后接下来了解了shell 的getopt用法。

看过官方文档后,自己写了个小demo

#!/bin/bash

#获取对应的参数 没有的话赋默认值
ARGS=`getopt -o a::b::l::n::t::p:: --long along::,blong::,llong::,plong:: -n 'example.sh' -- "$@"`
if [ $? != 0 ]; then
    echo "Terminating..."
    exit 1
fi

#echo $ARGS
#将规范化后的命令行参数分配至位置参数($1,$2,...)
eval set -- "${ARGS}"

while true;
do
    case "$1" in
        -a|--along)
            case "$2" in
                "")
                    project1_name=master;
                    shift 2;
                    ;;
                 *)
                    project1_name=$2;
                    shift 2;
                    ;;
            esac
             ;;
        -b|--blong)
            case "$2" in
                "")
                    project2_name=master;
                    shift 2
                    ;;
                 *)
                  project2_name=$2;
                    shift 2;
                    ;;
            esac
             ;;
        -l|--llong)
            case "$2" in
                "")
                    layer=layer_1;
                    shift 2
                    ;;
                *)
                    layer=$2;
                    shift 2;
                    ;;
            esac
            ;;
        -n)
            case "$2" in
                "")
                    number=1000;
                    shift 2
                    ;;
                *)
                    number=$2;
                    shift 2;
                    ;;
            esac
            ;;
        -t)
            case "$2" in
                "")
                    select_type=top;
                    shift 2
                    ;;
                *)
                    select_type=$2;
                    shift 2;
                    ;;
            esac
            ;;
         -p)
            case "$2" in
                "")
                    data_point=;
                    shift 2
                    ;;
                *)
                    data_point=$2;
                    shift 2;
                    ;;
            esac
            ;;

        --)
            shift
            break
            ;;
        *)
            echo "Internal error!"
            exit 1
            ;;
    esac

done

project1_name=${project1_name:-master}
project2_name=${project2_name:-master}
layer=${layer:-layer_1}
number=${number:-100}
select_type=${select_type:-top}
data_point=${data_point:-}

这一部分为输入参数对应的字符

a::b::l::n::t::p::

 

#-o表示短选项,两个冒号表示该选项有一个可选参数,可选参数必须紧贴选项,如-carg 而不能是-c arg

#--long表示长选项

一目了然,首先是根据传递过来的 是 -a  还是 -b  -l 进行判断,如果只有-a后面没有参数的话 则赋默认值,同时在

project1_name=${project1_name:-master}
project2_name=${project2_name:-master}
layer=${layer:-layer_1}
number=${number:-100}
select_type=${select_type:-top}
data_point=${data_point:-}

这一步 也进行了默认值的赋值操作。如果上面没有 project1_name  则赋值为master

例子如下:

参数的默认值设置

$cat myscript.sh

print ${1:-hello}

print ${2:-kshell}

$sh myscript.sh

hello

kshell

 

转载于:https://www.cnblogs.com/zhang-xiaoyu/p/9296217.html

Shell 脚本中,`getopts` 是一个用于解析命令行选项的内置命令,特别适用于处理短选项(如 `-a`、`b`)形式的参数。它通过循环依次读取选项参数,并将它们赋值给特定的内置变量,从而简化脚本参数的处理过程。 ### getopts 命令格式 `getopts` 的基本命令格式为: ```bash getopts OPTSTRING VAR ``` 其中: - `OPTSTRING` 定义了脚本支持的选项字符串,选项后若带有冒号 `:` 表示该选项需要一个参数- `VAR` 是变量名,用于存储当前解析到的选项。 ### 内置变量 - `OPTARG`:当选项需要参数时,该变量存储对应参数的值。 - `OPTIND`:表示当前选项在参数列表中的位置索引,初始值为 1。 ### 示例:使用 getopts 解析命令行参数 以下是一个使用 `getopts` 解析 `-e`、`-g`、`-t` `-p` 选项的脚本示例: ```bash #!/bin/bash ENV="" GROUP="" TYPE="" PLAYBOOK="" while getopts 'e:g:t:p:' var; do case "$var" in e) ENV="$OPTARG" ;; g) GROUP="$OPTARG" ;; t) TYPE="$OPTARG" ;; p) PLAYBOOK="$OPTARG" ;; ?) echo "Usage: $0 -e ENV -g GROUP -t TYPE -p PLAYBOOK" exit 1 ;; esac done # 显示解析后的参数 echo "Environment: $ENV" echo "Group: $GROUP" echo "Type: $TYPE" echo "Playbook: $PLAYBOOK" ``` 在上述脚本中: - 选项字符串 `'e:g:t:p:'` 表示每个选项都需要一个参数- 使用 `case` 语句匹配解析到的选项,并将对应的参数值赋给相应变量。 - 如果遇到未知选项(如 `-x`),则输出使用说明并退出脚本。 ### 选项处理的注意事项 - `getopts` 只支持短选项(如 `-a`),不支持长选项(如 `--option`)[^2]。 - 如果希望处理长选项,可以结合其他工具(如 `getopt`)[^3]。 - 选项参数之间可以使用空格分隔,也可以直接连接(如 `-ooutfile.txt`)[^3]。 ### 示例输出 假设运行脚本入如下命令: ```bash ./script.sh -e dev -g admin -t local -p deploy.yml ``` 输出结果为: ```bash Environment: dev Group: admin Type: local Playbook: deploy.yml ``` ### getoptsgetopt 的区别 - `getopts` 是 Bash 的内置命令,专门用于处理命令行选项,功能较为简单但易于使用[^2]。 - `getopt` 是外部工具,支持更复杂的选项处理逻辑,例如规范化选项顺序处理长选项[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值