1、shell中的数组
1.创建空数组
[root@tom shell]# arr=()
单个赋值
[root@tom shell]# arr[0]=1
[root@tom shell]# arr[1]=2
输出
[root@tom shell]# echo ${arr[0]}
[root@tom shell]# echo ${arr[1]}
2.创建非空数组,并输出
[root@tom shell]# arr1=(1 2 3 4 5)
[root@tom shell]# echo ${arr1[0]}
1
3.输出
输出某个元素,根据索引输出
[root@tom shell]# echo ${arr[0]}
1
输出所有的元素
echo ${arr[*]}/echo ${arr[@]}
[root@tom shell]# echo ${arr[*]}
1 2
[root@tom shell]# echo ${arr[@]}
1 2
获取数组的长度
echo ${#arr[*]}/echo ${#arr[@]}
[root@tom shell]# echo ${#arr[*]}
2
[root@tom shell]# echo ${#arr[@]}
2
遍历数组/数组的循环迭代
[root@tom shell]# vim shell_arr.sh
#!/bin/bash
:<<!
迭代数组
!
arr1=(a b c d 'abcd')
for i in ${arr1[*]}
do
echo $i
done
[root@tom shell]# chmod +x shell_arr.sh
[root@tom shell]# ./shell_arr.sh
a
b
c
d
abcd
2、shell运算符
常用的运算符
运算符 | 描述 |
---|---|
+ | 加 |
- | 减 |
* | 乘 |
/ | 除 |
% | 取余 |
运算的方式有2种
第一种
$(($a+$b))/$[$a+$b]
中间没有空格
[root@tom shell]# a=1
[root@tom shell]# c=2
[root@tom shell]# echo $[$a+$c]
3
[root@tom shell]# echo $[$a-$c]
-1
[root@tom shell]# echo $[$a*$c]
2
[root@tom shell]# echo $[$a/$c]
0