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

摘要:
已编写shell脚本。您需要将参数传输到shell脚本以供脚本使用。其效果是参数可以是可选的。下面是一个常规shell脚本:echo“要执行的文件名是:$0”;Echo“第一个参数名称是:$1”;Echo“第二个参数名是:$2”向shell脚本传递参数的常规方法是:/test sh123的最终执行结果是:执行的文件名为:./t

写了一个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.csdn.net/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
复制代码

免责声明:文章转载自《shell脚本传可选参数 getopts 和 getopt的方法》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇mysql8.0 初始化数据库及表名大小写问题es6模块化导入导出下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Linux declare命令

[ Linux 命令大全Linux declare命令用于声明 shell 变量。 declare为shell指令,在第一种语法中可用来声明变量并设置变量的属性([rix]即为变量的属性),在第二种语法中可用来显示shell函数。若不加上任何参数,则会显示全部的shell变量与函数(与执行set指令的效果相同)。 语法 declare [+/-][rxi...

Linux下通过shell进MySQL执行SQL或导入脚本

这条命令表示通过用户名和密码执行shell然后在shell里面执行一个建表语句: USER="root" PASS="root" mysql -u $USER -p$PASS <<EOF 2> /dev/null CREATE DATABASE um; EOF 下面的命令在登陆MySQL的时候指定了database(mysql): m...

shell网络管理

背景知识  联网就是通过网络将主机进行互联并采用不同的规范配置网络上的节点。我们以 TCP/IP 作为网络栈,所有的操作都是基于它进行的。网络是计算机系统中重要的部分。连接在网络上的每个节点都分配了一个用作标识作用的独一的 IP 地址。有很多联网参数,如子网掩码、路由、端口和 DNS 等,我们需要对这些知识有一个基本的理解。   Internet 依靠 T...

Linux shell awk中printf使用

printf 是 awk 的重要格式化输出命令printf格式化输出内容 格式:printf format,item1,item2...要点: 1,printf输出时要指定格式format2,formay用于指定后面的每个item输出的格式3,printf语句不会自动打印换行符 format格式: %c:显示单个字符%d,%i:十进制整数%e,%E:科学...

shell 字符串分割

语法1: substring=${string:start:len}   string的下标从0开始,以start可是,截取len个字符,并赋值于substring 1 #!/bin/bash 2 #substr=${string:start:len} 3 str="123456789" 4 substr=${str:3:3} 5 echo $su...

umilit 修改 linux 最多可打开文件数

ulimit -n 修改 临时修改: ulimit -SHn 65535 永久修改:echo'*-nofile65535'>>/etc/security/limits.conf Linux系统里打开文件描述符的最大值,一般缺省值是1024,对一台繁忙的服务器来说,这个值偏小,所以有必要重新设置linux系统里打开文件描述符的最大值。那么应该在...