- 一、shell介绍
- <1>shell是什么?
- <2>shell脚本文件格式
- 二、脚本执行的常用方式
- 1、==a.sh==:在当前目录查找(有条件)
- 2、==./a.sh== :明确在当前目录查找
- 3、==/usr/local/a.sh==:明确在当前目录查找
- 4、==bash a.sh==直接可以执行,甚至这个脚本文件中的第一行都可以不引(不用权限)
- 5、== bash -x a.sh==:bash的单步执行
- 6、==bash -n a.sh==:bash语法检查
- shell是用户与Linux操作系统沟通的桥梁
- Linux的shell种类众多,这里我们学习的是bash,也就是Bourne Again Shell
(1)由于易用和免费,bash在日常工作中被广泛使用
(2)bash是大多数Linux系统默认的shell
注:Linux里面操作的命令就叫shell命令
- 文件名后缀通常是.sh (放代码的文件)
(1)在/usr/local目录下创建目录shelldemo,执行vi进入demo.sh进入编辑模式
[root@hadoop61 ~]# cd /usr/local [root@hadoop61 local]# mkdir shellDemo [root@hadoop61 local]# cd shellDemo [root@hadoop61 shellDemo]# ll 总用量 0 [root@hadoop61 shellDemo]# vi demo.sh
(2)进入编辑模式后,在第一行写#!/bin/bash (特殊格式,可以理解为导包的过程)
注:#!/bin/bash 也可以写成#!/bin/sh
#!/bin/bash # this is comment echo "hello world!"
注:脚本里面第一个#号是一个特殊代符,除了第一行,后面#号开头的都是注释,下面的echo "hello world!"是我们输出的命令。
(3)查看一下demo.sh
[root@hadoop61 shellDemo]# more demo.sh #!/bin/bash # this is comment echo "hello world!"二、脚本执行的常用方式
注:a是一个变量,可以改的
| 命令 | 简介 |
|---|---|
| a.sh | 这样的话需要保证脚本具有执行权限并且在环境变量PATH中有(.),这样在执行的时候会先从当前目录查找 |
| ./a.sh | 只要保证这个脚本具有执行权限即可 |
| /usr/local/a.sh | 只要保证这个脚本具有执行权限即可 |
| bash a.sh | 直接可以执行,甚至这个脚本文件中的第一行都可以不引入/bin/bash,它是将hello.sh作为参数传给bash命令来执行的 |
| bash -x a.sh | bash的单步执行 |
| bash -n a.sh | bash语法检查 |
(1)在上面的more demo.sh看到输出了 “hello world!”,
执行demo.sh,发现显示权限不够
[root@hadoop61 shellDemo]# demo.sh -bash: ./demo.sh: 权限不够
(2)查看权限,再给文件所有者添加权限
[root@hadoop61 shellDemo]# ll 总用量 4 -rw-r--r--. 1 root root 53 10月 10 11:26 demo.sh [root@hadoop61 shellDemo]# chmod +x demo.sh
(3)这时再执行demo.sh,发现可以输出了
[root@hadoop61 shellDemo]# demo.sh hello world!
注:此时执行的demo.sh是没带路径的,不带路径的话,直接默认到path里面找
(5)查看环境变量,执行vi /etc/profile进去之后,定位到最下面,可以看到一下两行,export PATH=.:里的.:就代表的在当前路径
[root@hadoop61 shellDemo]# vi /etc/profile export JAVA_HOME=/data/soft/jdk1.8 export PATH=.:$JAVA_HOME/bin:$PATH
(6)如果删掉export PATH=.:里的.: 再source更新下
[root@hadoop61 shellDemo]# source /etc/profile
(7)开新会话输出$path查看下,发现.:删除成功
[root@hadoop61 ~]# echo $PATH /data/soft/jdk1.8/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
(8)定位到shellDemo,执行demo.sh,发现找不到命令(因为PATH里面没. 就不会到当前目录找,就会到PATH里面指定的路径找,脚本没在这些路径,所以找不到)
[root@hadoop61 shellDemo]# demo.sh -bash: demo.sh: 未找到命令2、./a.sh :明确在当前目录查找
不管PATH有没有配. 都可以执行(因为带了路径)
[root@hadoop61 shellDemo]# ./demo.sh hello world!3、/usr/local/a.sh:明确在当前目录查找
也可以直接执行/usr/local/a.sh(不管PATH有没有配. 都可以执行,因为带了路径)
[root@hadoop61 ~]# /usr/local/shellDemo/demo.sh hello world!4、bash a.sh直接可以执行,甚至这个脚本文件中的第一行都可以不引(不用权限)
[root@hadoop61 shellDemo]# bash demo.sh hello world!5、== bash -x a.sh==:bash的单步执行
[root@hadoop61 shellDemo]# bash -x demo.sh + echo 'hello world!' hello world!
- echo ‘hello world!’ :表示执行的echo命令
- hello world!:表示执行的结果
注:可以让我们看得更清晰,利于排查问题
看看脚本里有没有语法错误,没有输出代表没有问题
[root@hadoop61 shellDemo]# bash -n demo.sh [root@hadoop61 shellDemo]#



