zoukankan      html  css  js  c++  java
  • 小鸟初学Shell编程(二)编写简单的Shell脚本

    Shell脚本

    编写Python、PHP脚本通常需要掌握语言的函数,那么Shell脚本则不需要,只需要掌握Linux命令就可以编写Shell脚本,因为Shell脚本就是由多个Linux命令组成,通过将多个Linux命令组合保存成一个脚本文件,可直接给其他人使用。


    组合命令

    进入一个目录,查看目录的文件,这个过程分别需要执行两条命令,分别是cdls

    分开执行两个命令的形式如下:

    [root@lincoding usr]# cd /usr/
    [root@lincoding usr]#
    [root@lincoding usr]# ls
    bin  etc  games  include  lib  lib64  libexec  local  sbin  share  src  tmp
    [root@lincoding usr]#
    

    我们可以用分号;,来将两个命令组合在起来,顺序执行,那么一起执行的形式如下:

    [root@lincoding usr]# cd /usr/ ; ls
    bin  etc  games  include  lib  lib64  libexec  local  sbin  share  src  tmp
    [root@lincoding usr]#
    

    编写Shell脚本流程

    那么如果这两个命令经常使用或者提供给其他人使用,我们可以把这两个命令用Shell脚本文件保存起来。

    01 建立Shell脚本文件

    使用bash的Shell通常以.sh后缀

    [root@lincoding home]# touch test.sh
    

    02 编写Shell脚本

    通过vi命令编写test.sh脚本,内容如下:

    cd /usr/
    ls
    

    需要注意的是Shell脚本里每条语句后面不用加分号;,每条命令采用换行的方式,执行Shell脚本的时候就会顺序执行。

    03 给予Shell脚本执行权限

    因为建立文件的时候,默认是没有执行权限的,我们需要给予脚本执行权限,脚本才可以运行

    [root@lincoding home]# chmod u+x test.sh
    

    查看脚本权限

    [root@lincoding home]# ls -l test.sh
    -rwxr--r--. 1 root root 13 Sep 12 09:10 test.sh
    

    04 执行Shell脚本

    用bash执行Shell脚本,执行的结果就和我们在外边单行组合命令执行的结果是一样的

    [root@lincoding home]# bash test.sh
    bin  etc  games  include  lib  lib64  libexec  local  sbin  share  src  tmp
    

    声明Shell解释器

    那么这里还要考虑一下其他的问题,假设要把这个Shell脚本在与不同的系统下运行的时候就会有问题,如果系统默认的Shell不是bash,执行这个Shell脚本可能会失败,因为可能会有bash的一些Shell特性在里边。

    那么我们可以在Shell脚本文件的第一行声明它使用的是哪个Shell,书写的格式如下:

    #!/bin/bash
    

    这样写的好处是,执行Shell脚本的时候,会自动告诉系统用bash解释器的Shell来执行脚本。

    我们将刚才的test.sh脚本修改后如下:

    #!/bin/bash
    cd /usr/
    ls
    

    那么声明使用哪个Shell解释器后,我们执行脚本的方式就可以变的很简单了

    [root@lincoding home]# ./test.sh
    bin  etc  games  include  lib  lib64  libexec  local  sbin  share  src  tmp
    

    小结

    我们编写Shell脚本时,第一行要以#!/bin/bash声明Shell解释器,编写完后要给予Shell执行权限,接着就可以执行运行了。


  • 相关阅读:
    shell脚本之数组
    shell脚本之函数
    shell脚本之sed
    shell脚本的for循环与read
    shell脚本之if语句
    shell脚本正则表达式
    shell的编程原理
    《梦断代码》阅读笔记03
    12.19学习总结
    《梦断代码》阅读笔记02
  • 原文地址:https://www.cnblogs.com/xiaolincoding/p/11601016.html
Copyright © 2011-2022 走看看