博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
shell特殊位置变量
阅读量:7043 次
发布时间:2019-06-28

本文共 2276 字,大约阅读时间需要 7 分钟。

1.shell中特殊且重要的变量

1.1 shell中的特殊位置参数变量

在shell脚本中有一些特殊且重要的变量,例如:$0、$1、$#,称它们为特殊位置参数变量。需要从命令行、函数或脚本执行等传参时就要用到位置参数变量。下图为常用的位置参数:

shell特殊位置变量

(1) $1 $2...$9 ${10} ${11}特殊变量实战

范例1:设置15个参数($1~$15),用于接收命令行传递的15个参数。

[root@shellbiancheng ~]# echo \${1..15}$1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15[root@shellbiancheng ~]# echo echo \${1..15}echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15[root@shellbiancheng ~]# echo echo \${1..15}>m.sh[root@shellbiancheng ~]# cat m.sh echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15[root@shellbiancheng ~]# echo {a..z}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

执行结果如下:

[root@shellbiancheng ~]# sh m.sh {a..z}a b c d e f g h i a0 a1 a2 a3 a4 a5

当位参数数字大于9时,需要用大括号引起来

[root@shellbiancheng ~]# cat m.sh echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15}[root@shellbiancheng ~]# sh m.sh {a..z}a b c d e f g h i j k l m n o

(2)$0特殊变量的作用

$0的作用为取出执行脚本的名称(包括路径)。

范例2:获取脚本的名称及路径

[root@shellbiancheng jiaobenlianxi]# cat b.shecho $0

不带路径输出脚本的名字

[root@shellbiancheng jiaobenlianxi]# sh b.sh b.sh

带全路径执行脚本输出脚本的名字还有路径

[root@shellbiancheng jiaobenlianxi]# sh /home/linzhongniao/jiaobenlianxi/b.sh /home/linzhongniao/jiaobenlianxi/b.sh

有关$0的系统生产场景如下所示:

[root@shellbiancheng ~]# tail -6 /etc/init.d/rpcbind echo $"Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart|try-restart}"RETVAL=2;;esacexit $RETVAL

(3)$#特殊变量获取脚本传参个数实战

范例3:$#获取脚本传参的个数

[root@shellbiancheng ~]# cat m.sh  echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15}echo $#[root@shellbiancheng ~]# sh m.sh {a..z}a b c d e f g h i j k l m n o  只接受15个变量,所以打印9个参数26  传入26个字符作为参数

(4)$*和$@特殊变量功能及区别说明

范例4:利用set设置位置参数(同命令行脚本的传参)

[root@shellbiancheng ~]# set -- "I am" linzhongniao[root@shellbiancheng ~]# echo $#2[root@shellbiancheng ~]# echo $1I am[root@shellbiancheng ~]# echo $2linzhongniao

测试$*和$@,不带双引号

[root@shellbiancheng ~]# echo $*I am linzhongniao[root@shellbiancheng ~]# echo $@I am linzhongniao

带双引号

[root@shellbiancheng ~]# echo "$*"I am linzhongniao[root@shellbiancheng ~]# echo "$@"I am linzhongniao[root@shellbiancheng ~]# for i in "$*";do echo $i;done $*引用,引号里的内容当做一个参数输出I am linzhongniao[root@shellbiancheng ~]# for i in "$@";do echo $i;done $@引用,引号里的参数均以独立的内容输出I amlinzhongniao

转载于:https://blog.51cto.com/10642812/2298641

你可能感兴趣的文章
RHCE认证培训+考试七天实录(三)
查看>>
戴尔EqualLogic主机软件:新意何在?为何值得我关注?
查看>>
centos 6.5 编译安装 mysql 5.5.40
查看>>
统一应用版本,提高用户体验
查看>>
vsftpd服务
查看>>
cocos2d-x学习笔记番外篇05:如何快速屏蔽触摸
查看>>
最大子序列和问题
查看>>
我的友情链接
查看>>
CentOS6+Apache2+Django1.4的配置
查看>>
CCNA 08 rip 路由协议简介
查看>>
TCP/IP详解学习笔记(11)-TCP交互数据流,成块数据流
查看>>
PHP 笛卡尔积
查看>>
linux安装python3
查看>>
一文了解阿里云CDN HTTP2.0
查看>>
“迁移策略+新容器运行时”应对有状态应用的冷热迁移挑战
查看>>
[转载] spring boot集成tk.mybatis3.4.0通用mapper, java.lang.ClassCastException,实体不能转换为实体...
查看>>
chcon命令
查看>>
如何设置打开PL/SQL预加载之前的sql文本内容
查看>>
Struts2笔记(1)-----Struts2简介与工作原理
查看>>
好程序员教你正确规避java编程中的bug
查看>>