小鸟初学Shell编程(二)编写简单的Shell脚本

Shell脚本

编写Python、PHP脚本一般须要掌握语言的函数,那么Shell脚本则不须要,只须要掌握Linux命令就能够编写Shell脚本,由于Shell脚本就是由多个Linux命令组成,经过将多个Linux命令组合保存成一个脚本文件,可直接给其余人使用。bash


组合命令

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

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

[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]#

咱们能够用分号;,来将两个命令组合在起来,顺序执行,那么一块儿执行的形式以下:test

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

编写Shell脚本流程

那么若是这两个命令常用或者提供给其余人使用,咱们能够把这两个命令用Shell脚本文件保存起来。coding

01 创建Shell脚本文件

使用bash的Shell一般以.sh后缀权限

[root@lincoding home]# touch test.sh

02 编写Shell脚本

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

cd /usr/
ls

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

03 给予Shell脚本执行权限

由于创建文件的时候,默认是没有执行权限的,咱们须要给予脚本执行权限,脚本才能够运行语言

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

查看脚本权限di

[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执行权限,接着就能够执行运行了。

相关文章
相关标签/搜索