加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 01:40:48 所属栏目:安全 来源:网络整理
导读:? ? ? ? ? ? ? ? ? ? ? ? ? ?? Bash Shell中的特殊位置变量及其应用 ? ? ? 众所周知bash shell中有许多特殊的位置变量,灵活使用它们可以更好地发挥Shell脚本的功用。 即位置变量:$1,$2,...来表示,用于让脚本在脚本代码中调用通过命令行传递给它的参数

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

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

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

特殊变量:$?,$0,$*,[email?protected],$#,$$

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

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

$0 :? 表示命令本身

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

[email?protected] :?表传递给脚本的所有参数,每个参数为独立字符串

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

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

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

[[email?protected] ~]# echo $SHELL
/bin/bash

?[[email?protected] ~]# vim test_arg.sh?

[[email?protected] ~]# 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
[[email?protected] ~]#

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


?

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

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

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

?

?[[email?protected] ~]# ./get-ip.sh lo

The ip is 127.0.0.1
Thank you for using!
[[email?protected] ~]# ./get-ip.sh ens33
The ip is 192.168.1.19
Thank you for using!
[[email?protected] ~]# ./get-ip.sh virbr0
The ip is 192.168.122.1
Thank you for using!

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读