shell学习笔记2-逻辑控制

1、if结构

  • if [ condition ] ;then …fi;
  • if [ condition ]; then …else…fi;
  • if [ condition ];then …elif [ conditon ]; then …fi;
  • 简单的逻辑判断可以用&&||代替
# if 基本用法
[root@VM_0_2_centos home]# if [ 2 -eq 2 ];then echo "相等";fi
相等
# if ..else 用法
[root@VM_0_2_centos home]# if [ 3 -eq 2 ];then echo "相等"; else echo "不相等";fi
不相等
# if...elif用法
[root@VM_0_2_centos home]# if [ 3 -gt 2 ];then echo "大于";elif [ 1 -lt 2 ] ;then echo "小..";else echo "等于";fi
大于
# 使用&&和||
[root@VM_0_2_centos home]# ls
a.txt
[root@VM_0_2_centos home]# [ -f a.txt ] && echo "is file"
is file
[root@VM_0_2_centos home]# [ -f a.txt ] || echo "is file"
[root@VM_0_2_centos home]# [ -d a.txt ] || echo "is file"
is file

2、for循环

  • for循环
  • for ((c1;c2;c3));do…done;
[root@VM_0_2_centos home]# for((i=0;i<5;i++));do echo $i;done
0
1
2
3
4
  • for 遍历循环
  • for i in ${array[*]};do…done;
[root@VM_0_2_centos home]# for i in ${array[@]};do echo $i;done
1
2
3
4
5
[root@VM_0_2_centos /]# for i in `ls`;do echo $i;done
bin
boot
...

3、while循环

  • while循环
  • i=0;while [ condition ];do…;done
[root@VM_0_2_centos /]# i=0;while [ $i -lt 3 ];do echo $i;((i=i+1));done
0
1
2
  • 一行行读取文本内容
[root@VM_0_2_centos home]# while read line;do echo $line;done <a.txt 
hello world
hello java
hello python
hello ios
hello andriod

4、退出控制

  • return 函数退出
  • exit 脚本退出
  • break 退出当前循坏,默认为1
  • break 2 退出2层循环
  • continue 跳出当前循坏,进入下一次循环
  • continue 2 跳到上层循环的下次循环
[root@VM_0_2_centos home]# cat b.sh 
for((i=0;i<5;i++));
do
#[[ $i -eq 3 ]] && continue
#[[ $i -eq 3 ]] && break
[[ $i -eq 3 ]] && exit
echo $i
done
# exit用法
[root@VM_0_2_centos home]# bash b.sh 
0
1
2
# break用法
[root@VM_0_2_centos home]# bash b.sh 
0
1
2
# continue用法
[root@VM_0_2_centos home]# bash b.sh 
0
1
2
4

5、shell运行环境概念

  • bash是一个进程
    • bash下还可以再重新启动一个新shell,这个shell是sub shell,原shell会复制自身给它
    • 在子shell中定义的变量,会随的shell消亡而消亡
  • () 子shell中运行
  • {} 当前shell执行
  • $$ 当前脚本执行的PID
  • & 后台执行
  • $! 运行在后台的最后一个作业的PID(即进程ID)

猜你喜欢

转载自blog.csdn.net/LiaoBin0608/article/details/106710084