Shell脚本基础学习(一)----脚本格式、注释以及运行

来源:互联网 发布:js实例化对象的方法 编辑:程序博客网 时间:2024/06/06 04:26
Shell脚本的关键:输入多个命令并处理每个命令的结果。

1.shell脚本第一行格式:#!/bin/bash
一般#在shell中是用作注释行的,但是第一行的#是一个特例,#后的!告诉shell使用哪个shell来运行脚本,上面是用bash shell来运行脚本。也可以使用/bin/sh等。

2.注释
使用#来添加注释行。以#号开头的行都不会被shell处理(除了第一行)。

3.命令
接下来就可以在shell脚本中输入命令了。可以一行输入一个命令,也可以一行输入几个命令用分号隔开。这样一个简单的shell脚本就写好了。
#!/bin/bash
#my firdt shell
date
echo Hello World!

4.运行
上面的脚本保存的testsh中,直接在命令行输入testsh:
mengqin.zhang@U-mengqin-zhang:~/Documents$ testsh
testsh: command not found
bash shell找不到这个teshsh脚本。
shell通过PATH环境变量来查找命令,PATH环境变量的值:
mengqin.zhang@U-mengqin-zhang:~/Documents$ echo $PATH
/automount/tools:/automount/tools:/automount/tools:/automount/tools:/data/nishome/tdsw1/mengqin.zhang/bin:/data/nishome/tdsw1/mengqin.zhang/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
根本就不会在当前testsh所在的目录中查找,所以运行出问题。
解决方式:(1)在PATH中加入当前shell脚本所在的目录;(2)在提示符中使用绝对或相对路径来引用shell脚本文件。建议使用第二种。
mengqin.zhang@U-mengqin-zhang:~/Documents$ ./testsh
bash: ./testsh: Permission denied
使用第二种方式后,会提示Permission denied。
查看testsh的权限:-rw-r--r-- 1 mengqin.zhang tdsw1 0 Jun  1 10:38 testsh
发现没有可执行的权限。使用chmod更改权限:chmod u+x testsh
然后再次运行:
mengqin.zhang@U-mengqin-zhang:~/Documents$ ./testsh 
Wed Jun  1 10:56:06 CST 2016
Hello World!

以上,一个最最最简单的shell脚本就完成了。



1 0
原创粉丝点击