1、Bash脚本的基本使用
(1)read命令
read命令是用于从终端或者文件中读取输入的内部命令
读取整行输入
每行末尾的换行符不被读入
(2)read命令使用
从标准输入读取输入并赋值给变量
read var
从标准输入读取多个内容
read var1 var2 var3
不指定变量(默认赋值给REPLY )
read
2、脚本参数传递
$0 脚本名称
$1~$n 获取参数
$# 传递到脚本的参数个数
$$ 脚本运行的当前进程ID号
$* 以一个单字符串显示所有向脚本传递的参数
$? 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误
3、基本运算
(1)算术运算1
a=10 b=20
+ 加法
`expr $a + $b` -> 结果为30
- 减法
`expr $a - $b` -> 结果为-10
* 乘法
`expr $a \* $b` -> 结果为200
/ 除法
expr $b / $a` -> 结果为2
注意前后要加上``符号,运算符前后都有空格,乘法要将加\对*转义
(2)算数运算2
% 取余
`expr $a % $b` -> 结果为10
= 赋值
a=$b -> 将把变量b的值赋给a
== 相等相同则返回 true: [ $a == $b] -> 返回false
!= 不相等 不相同则返回true: [ $a !=$b ] -> 返回true
(3)算数运算3
-eq 检测相等 [ $a -eq $b ] 返回 false
-ne 检测不相等 [ $a -ne $b ] 返回 true
-gt 检测左边是否大于右边 [ $a -gt $b ] 返回 false
-lt 检测左边是否小于右边 [$a -lt $b ] 返回 true
-ge 检测左边是否大于等于右边 [ $a -ge $b ] 返回 false
-le 检测左边是否小于等于右边 [ $a -le $b ] 返回 true
4、Bash与Linux命令组合
(1)bash与目录命令
创建目录并生成文件
mkdir test
cd test
echo "hello" > test.txt
ls
(2)bash与内存
统计内存使用
for i in `ps aux | awk '{print $6}' I grep -v 'RSS'`
count=$[$count+$i]
echo "$count/kb"
5、实战
(1)read 命令
[root@static-ip-0 ~] read a
123
[root@static-ip-0 ~] echo $a
123
[root@static-ip-0 ~] read a b c
123 456 789
[root@static-ip-0 ~] echo $a
123
[root@static-ip-0 ~] echo $b
456
[root@static-ip-0 ~] echo $c
789
[root@static-ip-0 ~] read
456
[root@static-ip-0 ~] echo $REPLY
456
(2)bash脚本
2.1 基本练习
vim test.sh创建脚本如下
#!/bin/bash
echo $1,$2,$3
echo "文件名 "$0
echo "参数数量"$#
echo "all "$*
echo "return "$?
bash test.sh 1 2 3运行
[root@static-ip-0 ~] bash test.sh 1 2 3
1,2,3
文件名 test.sh
参数数量3
all 1 2 3
return 0
2.2 算数运算练习
vim test.sh修改脚本如下
#!/bin/bash
a=10
b=20
echo `expr $a + $b`
echo `expr $a - $b`
echo `expr $a \* $b`
echo `expr $a / $b`
echo `expr $a % $b`
运行结果
30
-10
200
0
10
2.3 进行判断
#!/bin/bash
a=10
b=20
if [ $a -lt $b ]
then
echo "eqal"
fi
结果:equl
也可以直接在命令行中运行
[root@static-ip-0 ~]# if [ 10 -gt 5 ]; then echo "big"; fi
big
[root@static-ip-0 ~]# if [ 10 -gt 5 ]
> then
> echo "big"
> fi
big
2.4 综合练习
创建脚本如下
#!/bin/bash
mkdir test
cd test
echo "hello" > test.txt
cat test.txt
运行结果
[root@static-ip-0 ~]# bash test.sh
hello
[root@static-ip-0 ~]# ls | grep test
test
test.sh
[root@static-ip-0 ~]# cd test
[root@static-ip-0 test]# cat test.txt
hello