zoukankan      html  css  js  c++  java
  • Bash Shell中的特殊位置变量及其应用

                                Bash Shell中的特殊位置变量及其应用

          众所周知bash shell中有许多特殊的位置变量,灵活使用它们可以更好地发挥Shell脚本的功用。

    即位置变量:$1,$2,...来表示,用于让脚本在脚本代码中调用通过命令行传递给它的参数

    特殊变量:$?, $0,$*,$@,$#, $$

    ---------------- 具体解析 -----------------------------

    $? : 用于检测上一条命令的返回码,0代表成功,1-255表示失败

    $0 :  表示命令本身

    $*  : 表传递给脚本的所有参数,全部参数合为一个字符串

    $@ : 表传递给脚本的所有参数,每个参数为独立字符串

    $# :  传递给脚本的参数的个数

    $$ :  获取当前执行的Shell脚本的进程号

    为了更好理解,我编写如下脚本进行测试,注意$10要括号括起来才能识别。

    [root@Franklin13 ~]# echo $SHELL
    /bin/bash

     [root@Franklin13 ~]# vim test_arg.sh 

    [root@Franklin13 ~]# bash test_arg.sh {a..z}

    1st arg is a
    2st arg is b
    10st arg is j
    All arg is a b c d e f g h i j k l m n o p q r s t u v w x y z
    All arg is a b c d e f g h i j k l m n o p q r s t u v w x y z
    The arg number is 26
    The scriptname is test_arg.sh
    [root@Franklin13 ~]#

    实战1: 活用$1来编写一个自动取ip的脚本


    首先用如下命令来截取ip, 成功了

    [root@Franklin13 ~]# ifconfig ens33|grep -w "inet"|tr -s ' ' %|cut -d% -f3 (tr -s ' ' %表示先压缩所有重复的空格到只留一个再转换为%)
    192.168.1.19

    再通过调用$1来使这条命令可以用于一个脚本来快速查ip。

     

     [root@Franklin13 ~]# ./get-ip.sh lo

    The ip is 127.0.0.1
    Thank you for using!
    [root@Franklin13 ~]# ./get-ip.sh ens33
    The ip is 192.168.1.19
    Thank you for using!
    [root@Franklin13 ~]# ./get-ip.sh virbr0
    The ip is 192.168.122.1
    Thank you for using!

     --------------------------------全文完-----------------------------------

     

  • 相关阅读:
    闽江学院2015-2016学年下学期《软件测试》课程-第五次博客作业
    在Swift中应用Grand Central Dispatch(下)
    在Swift中应用Grand Central Dispatch(上)转载自的goldenfiredo001的博客
    Asp.net mvc 框架揭秘之Asp.net +Mvc简介
    JavaScript数组
    网页校验
    删除弹出提示框_MVC
    业务体会
    判断数组值是否有重复
    sql
  • 原文地址:https://www.cnblogs.com/Franklinhong-No1/p/11565004.html
Copyright © 2011-2022 走看看