一、基础
1.test测试语句
echo $?为0代表上个语句执行成功
echo $?为1代表上个语句执行失败
test 1 = 1 echo $? test 1 = 2 echo $?
2.逻辑运算
&& 与
[ 1 = 1 ] && [ 2 = 2 ] [ 1 = 2 ] && [ 2 = 2 ]
|| 或
[ 1 = 1 ] || [ 2 = 2 ] echo $? [ 1 = 2 ] || [ 2 = 2 ] echo $?
3.类型判断
判断输入的是否是个文件
如果1.txt存在就查看
[ -f 1.txt ] && cat 1.txt
如果o目录存在就进入并输出里面存在的文件
[ -d o ] && cd o && ls -l
判断输入内容是否可以执行
[root@localhost o]# [ -x 1.txt ] && echo "can excute" [root@localhost o]# chmod 777 1.txt [root@localhost o]# [ -x 1.txt ] && echo "can excute"
4.数值判断
[ 2 -eq 1 ] echo $? [ 2 -eq 2 ] echo $? [ 2 -lt 2 ] echo $? [ 2 -gt 2 ] echo $? [ 2 -ne 1 ] echo $?
5.字符串比较
[root@localhost o]# str2="asdqewqr" [root@localhost o]# str1="asdsad" [root@localhost o]# [ str1 == str2 ] [root@localhost o]# echo $? [root@localhost o]# [ str1 != str2 ] [root@localhost o]# echo $?
6.计算表达式
[root@localhost o]# echo $((1+3)) [root@localhost o]# echo $((1+3)) [root@localhost o]# a=$((1+3)) [root@localhost o]# echo a [root@localhost o]# echo $a [root@localhost o]# echo $((a*3)) [root@localhost o]# echo let a [root@localhost o]# echo let a*2 [root@localhost o]# let a = a*2 [root@localhost o]# let a=a*2 [root@localhost o]# echo $a
二、shell数组
1.单行定义
[root@localhost o]# arr=(1 2 3 4 5 6) [root@localhost o]# echo $arr
2.多行定义
[root@localhost o]# arr2=( > 1 > 2 > 3 > 4 > 5 > 6 > 7 > ) [root@localhost o]# echo arr2
3.单元素定义
arr2[2]=10 arr2[3]=10 arr2[4]=10
4.查看元素
[root@localhost o]# echo ${arr2[2]} [root@localhost o]# echo ${arr2[3]} [root@localhost o]# echo ${arr2[4]} [root@localhost o]# echo ${arr1[4]} [root@localhost o]# echo ${arr1[1]} [root@localhost o]# echo ${arr[1]}
5.基于内容找索引
当不知道内容是什么的时候,可以查看所有下标
[root@localhost o]# echo ${!arr[*]} [root@localhost o]# echo ${!arr[@]} [root@localhost o]# echo ${!arr2[@]}
不加!可以看内容
6.增删改
获取元素
root@ou-virtual-machine:~# arr=(10000 200000 30000 40000 500000 600000) root@ou-virtual-machine:~# echo ${arr[0]:0:2} root@ou-virtual-machine:~# echo ${arr[3]:0:2} root@ou-virtual-machine:~# echo ${arr[3]:0:4}
更改元素
root@ou-virtual-machine:~# echo ${arr[3]} root@ou-virtual-machine:~# arr[3]=900000 root@ou-virtual-machine:~# echo ${arr[3]}
root@ou-virtual-machine:~# echo ${arr[3]} root@ou-virtual-machine:~# arr[3]=900000 root@ou-virtual-machine:~# echo ${arr[3]}
删除数组
unset删除单个数组元素
root@ou-virtual-machine:~# echo ${arr[*]} root@ou-virtual-machine:~# unset arr[1] root@ou-virtual-machine:~# echo ${arr[*]}
删除整个数组
unset 数组名