• shell_40.Linux特殊参数变量


    特殊参数变量
    (1)特殊变量$#含有脚本运行时携带的命令行参数的个数。可以在脚本中的任何地方使用这个特殊变量,就跟普通变量一样:

    1. $ cat countparameters.sh 
    2. #!/bin/bash 
    3. # Counting command-line parameters 
    4. if [ $# -eq 1
    5. then 
    6.     fragment="parameter was" 
    7. else 
    8.     fragment="parameters were" 
    9. fi 
    10.     echo $# $fragment supplied. 
    11. exit 
    12. $ ./countparameters.sh 
    13. 0 parameters were supplied. 
    14. $ ./countparameters.sh Hello 
    15. 1 parameter was supplied. 
    16. $ ./countparameters.sh Hello World
    17. 2 parameters were supplied. 
    18. $ ./countparameters.sh "Hello World" 
    19. 1 parameter was supplied. 
    20. $

    (2)可以在使用之前测试命令行参数的数量:

    1. $ cat addem.sh 
    2. #!/bin/bash 
    3. # Adding command-line parameters 
    4. if [ $# -ne 2 ]                     #######if-then 语句用-ne 测试检查命令行参数数量。如果数量不对,则会显示一条错误消息,告知脚本的正确用法
    5. then 
    6.     echo Usage: $(basename $0) parameter1 parameter2 
    7. else 
    8.     total=$[ $1 + $2
    9.     echo $1 + $2 is $total 
    10. fi 
    11. exit 
    12. $ ./addem.sh 
    13. Usage: addem.sh parameter1 parameter2 
    14. $ ./addem.sh 17 
    15. Usage: addem.sh parameter1 parameter2 
    16. $ ./addem.sh 17 25 
    17. 17 + 25 is 42 
    18. $

    (3)如果仔细考虑过,你可能会觉得既然$#变量含有命令行参数的总数,那么变量${$#}应该就代表了最后一个位置变量:

    1. $ cat badlastparamtest.sh 
    2. #!/bin/bash 
    3. # Testing grabbing the last parameter 
    4. echo The number of parameters is $# 
    5. echo The last parameter is ${$#} 
    6. exit 
    7. $ ./badlastparamtest.sh one two three four 
    8. The number of parameters is 4 
    9. The last parameter is 2648 

    (4)显然,这种方法不管用。这说明不能在花括号内使用$,必须将$换成!。很奇怪,但的确有效:

    1. $ cat goodlastparamtest.sh 
    2. #!/bin/bash 
    3. # Testing grabbing the last parameter 
    4. echo The number of parameters is $# 
    5. echo The last parameter is ${!#} 
    6. exit 
    7. $ ./goodlastparamtest.sh one two three four 
    8. The number of parameters is 4 
    9. The last parameter is four 
    10. $ ./goodlastparamtest.sh 
    11. The number of parameters is 0 
    12. The last parameter is ./goodlastparamtest.sh 


    完美。重要的是要注意,当命令行中没有任何参数时,$#的值即为 0,但${!#}会返回命令行中的脚本名。

  • 相关阅读:
    搞定!详解MeterSphere 配置外部Mysql5.7的全过程
    ElasticSearch
    STM32F1与STM32CubeIDE编程实例-金属触摸传感器驱动
    nginx.4——正向代理和反向代理(七层代理和四层代理)
    RANSAC拟合直线和平面
    什么情况下使用微服务?
    CentOS 7 编译ZooKeeper C客户端
    java计算机毕业设计燕理快递中转站系统设计与实现MyBatis+系统+LW文档+源码+调试部署
    onnx删除无用属性
    大数据之cdh集群安装
  • 原文地址:https://blog.csdn.net/mmmmm168m/article/details/133970130