一、shell变量
1、变量分类
- 局部变量
局部变量在脚本或命令中定义,仅在当前shell实例中有效。 - 环境变量
所有的程序,包括shell启动的程序,都能访问环境变量。 - shell变量
shell变量是由shell程序设置的特殊变量。
2、定义变量、使用变量
hello_world="hw"
echo ${hello_world}
定义变量不需要使用$,使用变量时需要使用 ${}
3、只读变量
#!/bin/bash
name="daming"
readonly name
name="tom"
readonly 修饰后,变量不可以再被赋值,name=“tom” 执行出错。
4、删除变量
#!/bin/sh
name="daming"
unset name
echo $name
unset 修饰后,变量被删除,所以脚本没有任何输出
二、字符串
1、字符串拼接
name="tom"
res="hello, "${name}" !"
res1="hello, ${name} !"
echo $res $res1
2、获取字符串长度
name="tom"
echo ${#name} #输出 3
3、截取子串
string="hello world"
echo ${string:1:4} # 从下标为1开始截取长度为4的子串
三、数组
1、数组的定义
arr1=("hello" "world" "!")
arr2[0]="hello"
arr2[1]="world"
arr2[4]=66
两种方式均可,可以不使用连续的下标,而且下标的范围没有限制。
2、使用数组
arr2[0]="hello"
arr2[1]="world"
arr2[4]=66
echo ${arr2[1]} # world
echo ${arr2[@]} # hello world 66, 意思是读取所有元素
echo ${arr2[*]} # hello world 66, 意思是读取所有元素
echo ${arr2[1]} # 5, 获取数组下标为1的元素的长度
echo ${#arr2[*]} # 3, 获取数组长度
echo ${#arr2[*]} # 3, 获取数组长度