第一个shell脚本

概述

  1. shell是一个命令行解释器,它接收应用程序/用户命令,然后调用操作系统内核
  2. shell还是一个功能相当强大的编程语言、易编写、易调试、灵和性强

shell解析器

[root@slave2 ~]# cat /etc/shells 
/bin/sh
/bin/bash
/sbin/nologin
/usr/bin/sh
/usr/bin/bash
[root@slave2 bin]# ll | grep bash
-rwxr-xr-x. 1 root root    964544 Apr 10  2018 bash
lrwxrwxrwx. 1 root root        10 Jul  2  2018 bashbug -> bashbug-64
-rwxr-xr-x. 1 root root      6964 Apr 10  2018 bashbug-64
lrwxrwxrwx. 1 root root         4 Jul  2  2018 sh -> bash

 shell脚本入门

脚本格式

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

第一个shell脚本:shellworld

创建一个shell脚本,输出hello world!

[root@slave2 ~]# vim helloworld.sh
# 在helloworld.sh中输入如下内容
#!/bin/bash
echo 'hello world!'

 脚本的常用执行方式

  1. 采用bash或sh+脚本的相对路径或绝对路径(不用赋予脚本+x权限)
    [root@slave2 ~]# bash helloworld.sh 
    hello world!
    [root@slave2 ~]# sh helloworld.sh 
    hello world!
    [root@slave2 ~]# pwd
    /root
    [root@slave2 ~]# bash /root/helloworld.sh 
    hello world!
    [root@slave2 ~]# sh /root/helloworld.sh   
    hello world!
    
  2. 采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x
    # 无执行权限
    -rw-r--r--. 1 root root       32 Jan 18 07:12 helloworld.sh
    [root@slave2 ~]# ./helloworld.sh
    -bash: ./helloworld.sh: Permission denied
    
    # 为helloworld.sh添加执行权限
    [root@slave2 ~]# chmod 777 helloworld.sh
    -rwxrwxrwx. 1 root root       32 Jan 18 07:12 helloworld.sh
    
    [root@slave2 ~]# ./helloworld.sh 
    hello world!
    [root@slave2 ~]# /root/helloworld.sh 
    hello world!
     

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

第二个shell脚本:多命令处理

  • 需求:在/root/testshell/目录下创建一个banzhang.txt,在banzhang.txt文件种增加“I love cls”
    #!/bin/bash
    cd /root/testshell/
    touch banzhang.txt
    echo 'I love cls' >> banzhang.txt
    
原文地址:https://www.cnblogs.com/zxbdboke/p/10404015.html