编写Python、PHP脚本通常需要掌握语言的函数,那么Shell脚本则不需要,只需要掌握Linux命令就可以编写Shell脚本,因为Shell脚本就是由多个Linux命令组成,通过将多个Linux命令组合保存成一个脚本文件,可直接给其他人使用。
进入一个目录,查看目录的文件,这个过程分别需要执行两条命令,分别是cd 和ls。
分开执行两个命令的形式如下:
[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脚本文件保存起来。
使用bash的Shell通常以.sh后缀
[root@lincoding home]# touch test.sh通过vi命令编写test.sh脚本,内容如下:
cd /usr/ ls需要注意的是Shell脚本里每条语句后面不用加分号;,每条命令采用换行的方式,执行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用bash执行Shell脚本,执行的结果就和我们在外边单行组合命令执行的结果是一样的
[root@lincoding home]# bash test.sh bin etc games include lib lib64 libexec local sbin share src tmp那么这里还要考虑一下其他的问题,假设要把这个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执行权限,接着就可以执行运行了。
转载于:https://www.cnblogs.com/xiaolincoding/p/11601016.html
相关资源:JAVA上百实例源码以及开源项目