Shell脚本入门
1. shell脚本创建
1 | #! /bin/bash 【推荐】 |
2. shell脚本运行
- 全路径直接运行
- ./ 运行
1 | [root@hadoop001 shell]# /root/shell/wordcount.sh |
- sh 命令执行
1 | ####没有执行权限也可以执行 |
3.shell脚本调试
- 脚本首行 -x
1 | [root@hadoop001 shell]# vi wordcount.sh |
- sh -x 执行脚本 【推荐】
1 | [root@hadoop001 shell]# sh -x wordcount.sh |
4.变量
1 | [root@hadoop001 shell]# vi variable.sh |
- 静态变量: k=“v” k=‘v’ k=v 【推荐 字符串加双引号】
- 动态变量: k=`v`
=前后不能有空格
-
引用
$k ${k} 【推荐加上花括弧】
5.传参
1 | [root@hadoop001 shell]# vi parameter.sh |
-
参数传递 *.sh 后面的值, 用空格分隔
-
如果传入的参数要作为一个整体,用""括起来
1
2
3
4
5
6[root@hadoop001 shell]# sh parameter.sh "a b"
a b
个数:1
传递参数作为一个字符串显示:a b
PID:12168【PID】重要,杀死进程的时候必须知道准确的PID
6.数组
用括号括起来, 空格分隔
1 | [root@hadoop001 shell]# vi array.sh |
* 也可以换成@
7.if判断
- if后面的[]内前后要有空格 ==前后也要有空格
- 字符串比较最好加上""
1 | [root@hadoop001 shell]# vi if.sh |
elif
1 | #!/bin/bash |
-
判断数值
-
数字判断一些命令:
-gt是大于
-lt是小于
-eq是等于
-ne是不等于
-ge是大于等于
le是小于等于
1
2
3
4
5
6
7
8[root@hadoop001 shell]# vi number.sh
#!/bin/bash
if [ $1 -gt $2 ]
then echo "参数$1大于参数$2"
else echo "参数$1小于参数$2"
fi
[root@hadoop001 shell]# sh number.sh 2 4
参数2小于参数4 -
-
判断文件是否存在,是否为空
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26#!/bin/sh
# 说明:判断文件是否存在
myPath="/root/test"
myFile="/root/test/1.log"
# 这里的-x 参数判断$myPath是否存在并且是否具有可执行权限
if [ ! -x "$myPath" ]; then
mkdir "$myPath"
fi
# 这里的-d 参数判断$myPath是否存在
if [ ! -d "$myPath" ]; then
mkdir "$myPath"
fi
# 这里的-f参数判断$myFile是否存在
if [ ! -f "$myFile" ]; then
touch "$myFile"
fi
# 这里的-s参数判断$myFile是否为空
if [ -s "$myFile" ]; then
echo "hi"
else
echo "empty"
fi
8.循环
- for循环
1 | [root@hadoop001 shell]# vi for.sh |
-
while循环
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19[root@hadoop001 shell]# vi while.sh
#!/bin/bash
j=1
while(($j<10))
do
echo $j
let "j++"
done
[root@hadoop001 shell]# sh while.sh
1
2
3
4
5
6
7
8
9
9.分隔语法
1 | [root@hadoop001 shell]# vi split.sh |
1 | [root@hadoop001 shell]# vi split1.sh |