shell中数组的表示
方法:
array_name=(ele1 ele2 ele3 … elen)
举例:
[root@hadoop01 ~]# grid_alert_path="/u01/app/grid/diag/tnslsnr"
[root@hadoop01 ~]# grid_alert_path2="/u01/app/grid/diag/tnsl"
[root@hadoop01 ~]# alert=(${grid_alert_path} ${grid_alert_path2})
[root@hadoop01 ~]# echo ${alert[0]}
/u01/app/grid/diag/tnslsnr
[root@hadoop01 ~]#
注意事项:1、赋值号=两边不能有空格,必须紧挨着数组名和数组元素
2、数组内类型可以不同
[root@hadoop01 ~]# alert=(1 2 "www")
[root@hadoop01 ~]# echo ${alert[0]}
1
[root@hadoop01 ~]# echo ${alert[2]}
www
[root@hadoop01 ~]#
打印所有元素
[root@hadoop01 ~]# echo ${alert[*]}
1 2 www
[root@hadoop01 ~]#
shell中使用for循环遍历数组
[root@hadoop01 ~]# alert=(c d "www")
[root@hadoop01 ~]# for i in ${alert[@]}
> do
> echo ${i}
> done
c
d
www
[root@hadoop01 ~]#
shell中读取文本文件中的内容做变量
[root@hadoop01 ~]# more test.txt
1
0
2
[root@hadoop01 ~]# more test.sh
#!/bin/bash
for line in `cat test.txt`
do
echo ${line}
done
[root@hadoop01 ~]#
[root@hadoop01 ~]# sh test.sh
1
0
2
[root@hadoop01 ~]#
shell中使用if语句
[root@hadoop01 ~]# more test.txt
ucc
[root@hadoop01 ~]# more test.sh
#!/bin/bash
line=`cat test.txt`
if [ ${line}="succ" ];then
echo "succ"
fi
[root@hadoop01 ~]# sh test.sh
succ
[root@hadoop01 ~]#
注意:此处输出是不对的,因为文本内容并不是succ,二是ucc,if却判断为成功了。
原因是${line}="succ"这一句,中间缺少了空格。
修改后如下:
[root@hadoop01 ~]# more test.txt
ucc
[root@hadoop01 ~]# more test.sh
#!/bin/bash
line=`cat test.txt`
if [ ${line} = "succ" ];then
echo "succ"
fi
[root@hadoop01 ~]# sh test.sh
[root@hadoop01 ~]#
注意:此处没有了输出,才说明是正确的
注意事项:
if语句中的判断语法,等号两边需要加空格
补充
shell中的单引号和双引号的区别
结论:单引号中的字符串不会做任何处理
双引号中的字符串会做处理,如处理转义字符(\n)
[root@hadoop01 ~]# var1="\\n" #使用双引号
[root@hadoop01 ~]# var2='\\n' #使用单引号
[root@hadoop01 ~]# echo ${var1}
\n #处理了转义
[root@hadoop01 ~]# echo ${var2}
\\n #没有处理转义
[root@hadoop01 ~]#
即,如果希望字符串不做任何编号,则使用单引号即可。
shell中的变量加大括号和不加的区别
[root@hadoop01 ~]# var1='\\n'
[root@hadoop01 ~]# echo $var1vv
#注意,此处输出为空
[root@hadoop01 ~]# echo ${var1}vv
\\nvv #此处才是字符串进行了拼接
[root@hadoop01 ~]#
即,在使用变量时,外面加上大括号是可靠的。