美文网首页Linux运维进阶-Python,Docker,Shell
shell脚本中while 和shift 配和解决变长参数问题

shell脚本中while 和shift 配和解决变长参数问题

作者: My熊猫眼 | 来源:发表于2020-05-28 12:24 被阅读0次

    在shell脚本中,我们经常需要根据传递的参数个数来进行相应的处理,那么参数个数不定的情况下如何实现优雅的处理呢?

    1. 鄙人不才,一直先判断参数的总个数,然后执行对应的循环做处理,这样不是不可以,就是觉得怪怪的,作为一个进阶的运维人员,总得有更好的方法,不是吗?
    2. 在查看系统中自带脚本的时候,发现了如下的解决方法(学习系统中原生脚本的重要性):
    [root@localhost ~]# cat test.sh
    #!/bin/bash
    while [ $# -gt 0 ];do
            echo $1
            shift           #shift 语句会把位置参数进行移位操作. 这个是实现的关键.
    done
    [root@localhost ~]# ./test.sh "P1" "P2"
    P1
    P2
    [root@localhost ~]# ./test.sh
    [root@localhost ~]#
    

    查看下shift的具体帮助,其内容如下:

    [root@localhost ~]# help shift
    shift: shift [n]
        Shift positional parameters.
    
        Rename the positional parameters $N+1,$N+2 ... to $1,$2 ...  If N is
        not given, it is assumed to be 1.
    
        Exit Status:
        Returns success unless N is negative or greater than $#.
    [root@localhost ~]#
    

    从上面的帮助可以看出,如果shift 命令不带参数,那么就是“将位置参数向左移位,最左边的参数被丢掉"
    用上面的方法处理起来就优雅多了.

    本文原创,转载请注明出处

    相关文章

      网友评论

        本文标题:shell脚本中while 和shift 配和解决变长参数问题

        本文链接:https://www.haomeiwen.com/subject/amioahtx.html