目录
一、判断
(一)单分支
相当于“为真时执行,不为真时跳过”
1.写法
脚本中这样写:
if [ condition ]
then
程序
fi
命令行运行:
[root@hadoop-master ~]# a=25
[root@hadoop-master ~]# if [ $a -ge 18 ];then echo OK;fi
OK
无参数的时候报错:
[root@hadoop-master sh_test]# test.sh
./test.sh: 第 3 行:[: =: 期待一元表达式
避免无参数报错,实际中可以这样优化:
——>
执行结果:
[root@hadoop-master sh_test]# test.sh zxd
welcome!
[root@hadoop-master sh_test]# test.sh abd
2.组合判断
可以使用 -a 表示 and 逻辑,用-o表示或逻辑
[root@hadoop-master sh_test]# test.sh 25
welcome!
(二)多分支
1.if-else
语法:
if [ condition ]
then
程序
elif [ condition ]
then
程序
else
程序
脚本例子:
[root@hadoop-master sh_test]# ./test.sh zxd 20
welcome!
youth
报错:[ condition ]两端一定要有空格,否则报错!
2.case
语法:
case $var in
value1)
程序1
;;
value2)
程序2
;;
*)
其他
;;
esac
脚本例子:
[root@hadoop-master sh_test]# case_test.sh 6
other
二、循环
(一)for循环
语法1:使用双括号
for (( start;condition;var_changes ))
do
程序
done
累加脚本:
[root@hadoop-master sh_test]# vi add_to.sh
[root@hadoop-master sh_test]# add_to.sh 50
1275
[root@hadoop-master sh_test]# add_to.sh 100
5050
注意点
- $sum和$i
- 计算结果用$[]接收,否则会当做str
- 双小括号(())里面可以直接用数学运算符
语法2:使用in与{a..b}:
for var in vaule1 value2 value3
do
程序
done
遍历value值,继刚才那个脚本:
循环打印出了几个值(无传入参数汇报错,期待操作参数)
[root@hadoop-master sh_test]# add_to.sh 100
5050
windows
linux
macos
{a..b}也是用于遍历的
[root@hadoop-master sh_test]# add_to.sh
windows
linux
macos
1
2
3
4
5
6
7
8
9
10
使用循环理解 $@ 与 $* 区别:
参数本身是都能遍历的:
[root@hadoop-master sh_test]# par_test x y z a b
----------$*----------
x
y
z
a
b
----------$@----------
x
y
z
a
b
但是如果用引号将变量引起来,$*会被视为一个元素,将所有参数当成一个整体,而$@会依次将参数输出
[root@hadoop-master sh_test]# par_test x y z a b
----------$*----------
x y z a b
----------$@----------
x
y
z
a
b
(二)while循环
语法
中括号使用条件判断
while [ condition ]
do
程序
done
与for的区别:
(这里在未给sum赋初值时报错了,上面却不报错?)
- for会将循环的变量、控制条件以及变量的变化等定好,进行循环;while只进行条件判断,是继续循环还是退出
- 使用while时,一般会在外部将循环变量定出来,给初值,然后在循环体里面实现循环变量的改变
感想:shell的括号和空格实在太反人类辣!!!