1.脚本格式
脚本以 #!/bin/bash 开头(指定解析器)
2.第一个 Shell 脚本:helloworld
(1)需求:创建一个Shell脚本,输出helloworld
(2)案例实操:
➜ ~ touch helloworld.sh➜ ~ vim helloworld.sh# 在helloworld.sh中输入如下内容#!/bin/bashecho "helloworld"
(3)脚本的常用执行方式
第一种:采用 bash 或者 sh+ 脚本的相对路径或者绝对路径
sh+脚本的相对路径
➜ ~ sh ./helloworld.shhelloworld
sh+脚本的绝对路径
➜ ~ sh /root/helloworld.shhelloworld
bash脚本的相对路径
➜ ~ bash ./helloworld.shhelloworld
bash脚本的绝对路径
➜ ~ bash /root/helloworld.shhelloworld
第二种:采用输入脚本的绝对路径或者相对路径执行脚本(必须具有可执行权限 +x )
(1)首先要赋予 helloworld.sh 脚本的+x权限
➜ ~ chmod +x helloworld.sh
(2)执行脚本
相对路径
➜ ~ ./helloworld.shhelloworld
绝对路径
➜ ~ /root/helloworld.shhelloworld
注意: 第一种执行方法, 本质是 bash 解析器帮你执行脚本, 所以脚本本身不需要执行权限。 第二种执行方法, 本质是脚本需要自己执行, 所以需要执行权限。
【了解】第三种:在脚本的路径前面加上 “.” 或者 source
(1)有以下脚本
➜ ~ vim test.sh#!/bin/bashA=5echo $A
(2)分别使用 sh,bash,./ 和 . 的方式来执行,结果如下:
➜ ~ bash test.sh5➜ ~ echo $A➜ ~ sh test.sh5➜ ~ echo $A➜ ~ chmod +x test.sh➜ ~ ./test.sh5➜ ~ echo $A➜ ~ . test.sh5➜ ~ echo $A5
原因:
前两种方式都是在当前 shell 中打开一个子 shell 来执行脚本内容, 当脚本内容结束, 则子 shell 关闭, 回到父 shell 中。
第三种, 也就是使用在脚本路径前加“.” 或者 source 的方式, 可以使脚本内容在当前shell 里执行, 而无需打开子 shell! 这也是为什么我们每次要修改完/etc/profile 文件以后, 需要 source 一下的原因。
开子 shell 与不开子 shell 的区别就在于, 环境变量的继承关系, 如在子 shell 中设置的当前变量, 父 shell 是不可见的。
第三种:第二个Shell脚本:多命令处理
(1)需求:
在/home/atguigu/目录下创建一个banzhang.txt,在 banzhang.txt文件中增加”I love cls”。
(2)案例实操
~ touch batch.sh~ vim batch.sh#!/bin/bashcd /home/atguigu/touch banzhang.txtecho "I love cls" >> banzhang.txt#echo "I love cls" >> /home/atguigu/banzhang.txt
