1.脚本格式

脚本以 #!/bin/bash 开头(指定解析器)

2.第一个Shell脚本:helloshell

(1)需求:创建一个Shell脚本,输出helloshell
(2)案例实现

  1. [root@localhost ~]# touch hellshell.sh
  2. [root@localhost ~]# vim hellshell.sh
  3. #!/bin/bash
  4. echo "helloshell"

(3)脚本的常用执行方式

第一种:采用bash或sh+脚本的相对路径或绝对路径(不用赋予脚本+x权限)

  1. sh+脚本的相对路径 ```shell [root@localhost ~]# sh hellshell.sh helloshell
  1. 2. sh+脚本的绝对路径
  2. ```shell
  3. [root@localhost ~]# sh /root/hellshell.sh
  4. helloshell
  1. bash+脚本的相对路径 ```shell [root@localhost ~]# bash hellshell.sh helloshell
  1. 4. bash+脚本的绝对路径
  2. ```shell
  3. [root@localhost ~]# bash /root/hellshell.sh
  4. helloshell

第二种:采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x)

  1. 首先要赋予helloshllo.sh脚本可执行权限 ```shell [root@localhost ~]# chmod 777 hellshell.sh

    查看权限

    [root@localhost ~]# ll total 8 -rw———-. 1 root root 1292 Nov 25 03:52 anaconda-ks.cfg -rwxrwxrwx. 1 root root 31 Apr 15 05:11 hellshell.sh
  1. 2. 执行脚本
  2. ```shell
  3. # 相对路径
  4. [root@localhost ~]# ./hellshell.sh
  5. helloshell
  6. # 绝对路径
  7. [root@localhost ~]# /root/hellshell.sh
  8. helloshell

注意:第一种执行方法,本质是bash解析器帮你执行脚本,所以脚本本身不需要执行权限。第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。

3. 第二个Shell脚本:多命令处理

(1)需求:
用root用户在root用户的家目录下创建一个test.txt,在test.txt文件中增加“I love shell”
(2)需求实现

  1. # 创建test.sh文件
  2. [root@localhost ~]# touch test.sh
  3. # 编辑test.sh文件
  4. [root@localhost ~]# vim test.sh
  5. #!/bin/bash
  6. cd /root
  7. touch test.txt
  8. echo "I love shell" >> test.txt