概念
Shell脚本是包含一系列命令的文本文件
Shell读取此文件并执行命令
应用场景
- 重复性操作
- 批量事务处理
- 自动化运维
- 定时任务执行
编写脚本及流程控制
- 每一个shell都要有头的定义,正常是#!/bin/bash
- 打印: echo “要打印的东西”
vi test.sh
#!/bin/bash
echo Hello B shell!!
- 定义好的脚本需要加上执行权限: chmod +x 脚本路径
- 三种调用方式:
(1)路径调用 如果在当前目录,则使用 ./xxx.sh,绝对路径也可
(2)普通脚本执行: sh 脚本路径
(3)指定b shell 执行: /bin/bash 脚本路径
#!/bin/bash
a=1
b=$[$a+1]
c="b的值为${b}a"
d=3
e=$(($b+$d))
f=$[$b*$d]
result='ls -l'
echo $b
echo $c
echo $e
echo $f
echo `$result`
输出结果:
- 变量的定义
(1)直接赋值法 a=1 b=“abc” arr={1 2 3 4} 注:不能有空格
(2)引用赋值法 b=$
a c=$
{b}
撤销变量 unset 变量名
常量(只读变量) readonly 变量名=值
位置变量: $0代表命令本身,$1-$9代表顺序参数编号,大于10需要使用大括号, 如 ${10}
预定义变量
#!/bin/bash
echo $0
echo $@
echo "first args:$1"
echo "args count is:$#"
echo "all args:$*"
#$@ 将参数分割开来,一次一个的输出
#$* 将参数作为一个字符串一起输出
执行结果:
6. 执行变量的运算: (+、-、\*
、\
)
b=expr $a + 1
b=$[ $a + 1 ]
b=$(( $a + 1 ))
#注:引用后输出字符需要使用大括号括起来 ${a}b 避免歧义
-
数值型关系运算符
等于: -eq或==
-
字符串型 等于: ==或= 不等于: != 是否为空: -z 字符串
-
逻辑运算符
-
文件运算符
-
if条件语句
注:在判断条件中使用计算:在括号内侧及运算符两边都要加空格
格式:
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
#!/bin/bash
#a=$1
#if [ $a -lt 10 ]
#then
#echo 'less than 10'
#elif [ $a == 10 ]
#then
#echo 'equals 10'
#else
#echo 'great than 10'
#fi
a="abc"
b="abc"
if [ $a = $b ]
then
echo "abc"
fi
输出结果:
- if条件语句可省略成: [[ 条件语句 ]] && 结果语句
#!/bin/bash
a=1
b=2
[[ $a -lt $b ]] && echo "a<b"
输出结果:
- if test结构
使用if test可以省略if条件判断的[ ]
#!/bin/bash
a=1
b=2
if test $a -lt $b
then
echo "a<b"
- case条件语句
格式:
case $ in
1)commend1
;;
2)commend2
;;
...
...
*)commend*
;;
esac
#!/bin/bash
a=$1
case $a in
1)
echo '${a} is 1'
;;
2)
echo '${a} is 2'
;;
3)
echo '${a} is 3'
;;
*)
echo 'nothing here'
;;
esac
输出结果:
- for循环语句
语法:
用法1:
for var in paramters
do
command1
command2
...
commandN
done
用法2:
for(( ; ; ))
do
command1
command2
...
commandN
done
##!/bin/bash
#for a in 1 2 3 4 5 6 7 8 9 10
#do
#echo $a
#done
for((b=1;b<=10;b++))
do
echo $b
done
输出结果:
- while循环语句
语法:
while condition
do
command
done
#!/bin/bash
a=1
while [ $a -lt 10 ]
do
echo $a
let a++
done
输出结果:
- until循环语句
until 循环执行一系列命令直至条件为 true 时停止
语法
until condition
do
commend
done
#!/bin/bash
a=1
until [ $a -eq 10 ]
do
echo $a
let a++
done
输出结果:
- TMOUT语句
在用户出入空闲一段时间后自动断开,与用户输入read一起用
#!/bin/bash
TMOUT=10
echo "input your name in $TMOUT second"
read name
if [ $? -eq 0 ]
then
echo "your name is $name"
else
echo "time out"
fi