SHELL编程入门
一、hello world
- 新建学习文件夹:
mkdir shell_test
- 新建文件:
touch hello-world.sh
- 编写脚本:
vim hello-world.sh
#!/bin/bash
#关键词echo:输出
echo 'hello world'
- 执行脚本:
bash hello-world.sh
/sh hello-world.sh
二、编写一个多条语句的脚本
创建一个文件,并且插入一段内容
#!/bin/bash
touch newfile.txt
echo '文章内容插入' >> newfile.txt
三、变量
- export A:全局变量
- $n:表示命令后更的参数($0表示当前命令)
# 1、vim test_.sh
# 2、输入内容:
==========================
#!/bin/bash
echo "$0 $1 $2 $3"
==========================
输入:bash test_.sh
输出:test_.sh
输入:bash test_.sh a b c d
输出:test_.sh a b c
- $#:输出参数数量
# 2、输入内容:
==========================
#!/bin/bash
echo "$0 $1 $2 $3"
echo $#
==========================
输入:bash test_$ a b c d
输出:test_$ a b c
输出:4
- $ * 和 $@:输出所有参数
- $?:上一条命令的执行状态(0:正确执行,其他:报错)
四、运算符
- expr(计算数字之间必须要空格)
expr 3 + 2
expr 3 - 2
expr
expr 3 + 2\* 4
- $ [运算符]:
s=$[(3+2)*4]
echo $s
五、判断指令
- 判断条件:
(1)整数之间的比较:
小于:-lt
小于等于:-le
等于:-eq
大于:-gt
大于等于:-ge
不等于:-ne
(2)读写权限:
有读的权限:-r
有写的权限:-w
有读写的权限:-rw
(3)文件类型判断:
常规文件:-f
文件存在:-e
目录存在:-d
六、条件判断
1、if
范例:
if [ 条件判断 ]
then
满足条件业务逻辑
elif [ 条件判断 ]
then
满足条件业务逻辑
fi
实例:
#!/bin/bash
A=1
B=1
if [ $A -eq 1 ]
then
echo 'test-a1'
elif [ $B -eq 2 ]
then
echo 'test-b2'
fi
2、case
范例:
A=3
case $A in
'条件1')
逻辑业务
;;
'条件1')
逻辑业务
;;
'条件1')
逻辑业务
;;
esac
实例:
#!/bin/bash
A=3
case $A in
1)
echo 1
;;
2)
echo 2
;;
3)
echo 3
;;
esac
3、for
# 方式1
for(( i=1;i<=10;i=i+1 ))
do
echo $i
done
#方式2
for i in [数组]
do
echo $i
done
#!/bin/bash
# 方式1
for(( i=1;i<=10;i=i+1 ))
do
echo 'test'$i'.txt'
done
#方式2
for i in 11 22 33 44
do
echo $i
done
4、while
#!/bin/bash
i=0
while[ $i -le 10]
do
ehco $i
done
七、读取用户输入
- read
-t :等待用户输入时间
-p:输入提示
NAME:输入的参数
#!/bin/bash
read -t 7 -p "输入参数:" NAME
echo $NAME
八、函数
1、系统函数
- basename:截取路径中文件的名称
$ basename ./shell_read.sh
shell_read.sh
- dirname:返回文件路径
$ dirname /home/rcc/桌面/shell_test/shell_read.sh
/home/rcc/桌面/shell_test
2、自定义函数
案例 求和函数
#!/bin/bash
function sum()
{
s=0
# 参数1 + 参数2
s=$[ $1 + $2 ]
echo "$s"
}
read -p "数值1:" n1
read -p "数值2:" n2
sum $n1 $n2
3、cut 剪切文件文本
cut_bash.sh:
#!/bin/bash
echo "================剪切第一列================"
# 在data2.txt文件下追加剪切的数据
cut -d " " -f 1 data.txt >> data2.txt
# 在data2.txt文件下覆盖剪切的数据
cut -d " " -f 3 data.txt >> data3.txt
cut -d " " -f 1 data.txt
echo "================剪切第二,三列================="
cut -d " " -f 2,3 data.txt
data.txt:
1 2 3
1 2 3
1 2 3
1 2 3
结果:
4、sed 追加内容
追加操作:
指令:
-
错误处理
mac系统报错:
➜ bash sed "2a 666 666" sed.txt
sed: 1: "2a 666 666": command a expects \ followed by text
原因:mac自带的sed命令有点老
解决:brew install gnu-sed
-
案例
# 第二行追加 ‘666 666’ 源文件不改变
bash sed "2a \666 666" sed.txt
# 删除以 wo 开头的行
bash sed "/wo/d" sed.txt
# 删除第2行
bash sed "2d" sed.txt
# 替换
bash sed "s/wo/aa/g" sed.txt
# 将文件第2行删除 并将wo替换成aaa
bash sed -e "2d" -e "s/wo/aaa/g" sed.txt
5、sort 排序
# -t : 按照:分割 | -nr 依照数值大小倒叙 | -k 2 指定第2列排序
➜ bash sort -t : -nr -k 2 sort.txt
aa:70:4.1
cd:60:4.7
bd:50:4
bb:40:4.5
➜ bash sort -t : -n -k 2 sort.txt
bb:40:4.5
bd:50:4
cd:60:4.7
aa:70:4.1