1. 入门
- 一般脚本是以.sh结尾的,但有些没有
- which是从path环境变量查找
- 后缀是以.sh结尾
- #!/bin/bash
- chmod u+x wc.sh
- shell的debug有两种方式
- 变量要大写
root@zuozedata001 learn_shell]# sh -x wc.sh
echo ruozedata
ruozedata`
#在vim中
#!/bin/bash -x
echo "ruozedata"
~
2.变量与非变量
#!/bin/bash
rz="001"
date1="date"
date2=`date`
echo $rz
echo ${date1}
echo ${date2}
[root@zuozedata001 learn_shell]# ./variable.sh
001
date
Fri Aug 23 20:44:45 CST 2019
-
1. = 前后不能有空格
2.变量名称 一般来说 都是大写
3.使用变量 习惯的使用{} -
静态
k = “v” ‘v’ v (推荐"v") -
动态
k =v
3.传递参数
#!/bin/bash
echo $1
echo $2
echo "$#"
echo "$*"
echo "PID: $$" #执行的一刹那的pid
~
[root@zuozedata001 learn_shell]# ./parameter.sh a b
a
b
2
a b
PID: 2292
4.数组
#!/bin/bash
arr=(rz jepson xingxing huhu)
echo ${arr[@]}
echo ${arr[3]}
echo ${#arr[@]}
[root@zuozedata001 learn_shell]# ./array.sh
rz jepson xingxing huhu
huhu
4
5.if
#!/bin/bash
a="123"
b="345"
if [ $a == $b ]; then
echo "=="
else
echo "!="
fi
[root@zuozedata001 learn_shell]# chmod u+x if.sh
[root@zuozedata001 learn_shell]# ./if.sh
!=
- [ ]前后和==前后都要有空格
6.for while
[root@zuozedata001 learn_shell]# vi while.sh
#!/bin/bash
ffor x in 1 2 3 4 5
do
echo $x
done
echo "------------------"
for (( i=1;i<=10;i++ ))
do
echo $i
done
echo "------------------"
j=1
while (($j<9))
do
echo $j
let "j++"
done
[root@zuozedata001 learn_shell]# ./while.sh
1
2
3
4
5
------------------
1
2
3
4
5
6
7
8
9
10
------------------
1
2
3
4
5
6
7
8
7.分割
- 固定格式
#!/bin/bash
s="rz,j,xx,huhu.yt"
IFS=","
OLD_IFS=$IFS
arr=$s
IFS=$OLD_IFS
for x in ${arr[*]}
do
echo $x
done
[root@zuozedata001 learn_shell]# ./insection.sh
rz
j
xx
huhu.yt
8. awk
- 打印第一列
[root@zuozedata001 learn_shell]# vi test.log
a b c
1 2 3
[root@zuozedata001 learn_shell]# cat test.log | awk '{print $1}'
a
1
#打印第一列和第二列
[root@zuozedata001 learn_shell]# cat test.log | awk '{print $1,$2}'
a b
1 2
[root@zuozedata001 learn_shell]# cat test.log | awk '{print $1$2}'
ab
12
- 打印行
#打印第一行
[root@zuozedata001 learn_shell]# cat test.log | awk 'NR==1{print}'
a b c
#打印第一行的第一列
[root@zuozedata001 learn_shell]# cat test.log | awk 'NR==1{print $1}'
a
#打印第一行以外的
[root@zuozedata001 learn_shell]# cat test.log | awk 'NR>1{print}'
1 2 3
[root@zuozedata001 learn_shell]# vi test1.log
a,b,c
1,2,3
#指定符号分割
[root@zuozedata001 learn_shell]# cat test1.log | awk -F "," '{print $1}'
a
1
sed(用作替换)
#替换a为aa
[root@zuozedata001 learn_shell]# sed -i 's/a/aa/' test1.log
[root@zuozedata001 learn_shell]# cat test1.log
aa,b,c
1,2,3
[root@zuozedata001 learn_shell]# sed -i 's/aa/bbb/' test1.log
[root@zuozedata001 learn_shell]# cat test1.log
bbb,b,c
1,2,3
#全局替换
[root@zuozedata001 learn_shell]# sed -i 's/b/j/g' test1.log
[root@zuozedata001 learn_shell]# cat test1.log
jjj,j,c
1,2,3