shell 变量
定义变量
- 变量名和等号之间不能有空格
- 只能使用英文字母,数字和下划线,首个字符不能以数字开头
- 中间不能有空格
- 不能使用标点符号
- 不能使用bash里的关键字(可用help命令查看保留关键字)
name="zhangsan"
使用变量
[root@standalone ~]
[root@standalone ~]
张三
[root@standalone ~]
张三
修改变量
[root@standalone ~]
[root@standalone ~]
张三
[root@standalone ~]
[root@standalone ~]
李四
只读变量
[root@standalone ~]# url="www.baidu.com"
[root@standalone ~]# readonly url
[root@standalone ~]# url="www.jd.com"
-bash: url: 只读变量
删除变量
[root@standalone ~]# unset name
[root@standalone ~]# echo ${name}
shell 字符串
单引号 | 中不可使用变量,所有内容原样输出 |
---|
双引号 | 可以使用变量,可以使用转义 |
获取字符串长度
[root@standalone ~]# echo $url
www.baidu.com
[root@standalone ~]# echo ${#url}
13
截取字符串
[root@standalone ~]# echo ${url:5:2}
ai
# 从下表5开始,截取两个
shell 数组
定义数组
[root@standalone ~]# arr2[0]=0
[root@standalone ~]# arr2[1]=1
[root@standalone ~]# arr2[2]=2
[root@standalone ~]# arr1=(1 2 3 4 5 6)
读取数组
[root@standalone ~]# arr2[0]=0
[root@standalone ~]# arr2[1]=1
[root@standalone ~]# arr2[2]=2
[root@standalone ~]# arr1=(1 2 3 4 5 6)
[root@standalone ~]# echo ${arr1[0]}
1
[root@standalone ~]# echo ${arr1[@]}
1 2 3 4 5 6
获取数组长度
[root@standalone ~]# echo ${#arr1[*]}
6
[root@standalone ~]# echo ${#arr1[@]}
6
shell 注释
#--------------------------------------------
# 这是一个注释
#--------------------------------------------
##### 用户配置区 开始 #####
#
#
# 这里可以添加脚本描述信息
#
#
##### 用户配置区 结束 #####
:<<EOF
注释内容...
注释内容...
注释内容...
EOF