一、第一个Shell脚本

1.什么是shell脚本?
提前写好可执行的语句,能够完成特定任务的文件(顺序执行,批量化处理;解释型程序)

Shell系列-编写及执行脚本

2.shell版HelloWorld的诞生
脚本创建"三步走"
-新建文本文件
-添加可执行的脚本语句(命令行)
-添加x执行权限

[root@centos67-x64 /]# vim first.sh   //创建文件
#!/bin/bash
echo "Hello World"    //编写脚本语句
[root@centos67-x64 /]# chmod +x first.sh    //添加x权限
[root@centos67-x64 /]# ./first.sh     //运行脚本,查看运行结果
Hello World

二、脚本构成及执行

1.规范的脚本构成
#! :脚本声明(使用哪种解释器)
# :注释信息(步骤、思路、用途、变量含义等)
可执行的语句

#!/bin/bash   //sha-bang调用标记
#A test program for shell-script  //注释信息
echo "Hello World"      //可执行的脚本语句或命令行

2.脚本的执行方式
2.1 方法一(作为"命令字")
-指定脚本文件的路径,前提是有x权限
2.2 方法二(作为"参数")-不需要有x权限
-sh 脚本文件路径
-source 脚本文件路径
-.脚本文件路径

[root@centos67-x64 /]# sh first.sh 
Hello World
[root@centos67-x64 /]# ./first.sh 
Hello World

3.调试shell脚本
主要途径:
-直接观察执行中的输出、报错信息
-通过sh -x 开启调试模式
-在可能出错的地方设置echo断点

[root@centos67-x64 /]# sh -x first.sh 
+ echo 'Hello World'
Hello World

三、简单脚本应用

1.例-1:快速配置YUM
目的:为新装的客户机配置好YUM仓库
条件:软件源位于file:///misc/cd;通过脚本建立/etc/yum.repos.d/rhel6.repo文件

[root@centos67-x64 shell]# ls /etc/yum.repos.d/
repo
[root@centos67-x64 shell]# vim rhel6.sh
#!/bin/bash
rm -rf /etc/yum.repos.d/*.repo
echo '[repo]
name=rhel6 repo
baseurl=file:///misc/cd
enable=1
gpgcheck=0
gpgkey='> /etc/yum.repos.d/rhel6.repo
[root@centos67-x64 shell]# chmod +x rhel6.sh 
[root@centos67-x64 shell]# ./rhel6.sh 
[root@centos67-x64 shell]# ls /etc/yum.repos.d/
repo  rhel6.repo
[root@centos67-x64 shell]# cat /etc/yum.repos.d/rhel6.repo 
[repo]
name=rhel6 repo
baseurl=file:///misc/cd
enable=1
gpgcheck=0
gpgkey=

2.例-2:快速搭建FTP服务器
目的:为新装的客户机搭建好vsftpd服务
条件:安装vsftpd;开启服务;开机自启

[root@centos67-x64 shell]# vim ftpon.sh
#!/bin/bash
yum -y install vsftpd &> /dev/null
/etc/init.d/vsftpd restart
chkconfig vsftpd on
文章目录