Bash Shell中的特殊位置变量及其应用shell
众所周知bash shell中有许多特殊的位置变量,灵活使用它们能够更好地发挥Shell脚本的功用。vim
即位置变量:$1,$2,...来表示,用于让脚本在脚本代码中调用经过命令行传递给它的参数bash
特殊变量:$?, $0,$*,$@,$#, $$测试
---------------- 具体解析 -----------------------------spa
$? : 用于检测上一条命令的返回码,0表明成功,1-255表示失败命令行
$0 : 表示命令自己3d
$* : 表传递给脚本的全部参数,所有参数合为一个字符串blog
$@ : 表传递给脚本的全部参数,每一个参数为独立字符串进程
$# : 传递给脚本的参数的个数ip
$$ : 获取当前执行的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!
--------------------------------全文完-----------------------------------