配置Linux简单的脚本文件自启动

在Linux中使用shell脚本解决一些问题会比单独执行多条命令要有效率,脚本文件规定命名以.sh结尾,最基本的规则就是其内容是命令,想要脚本文件开机自启动,就需要把脚本文件放到/etc/init.d/目录下,此目录下的脚本文件是开机自启动脚本,脚本文件执行的基本要求是把命令单独放到命令行执行不会报错

1、执行命令cat /etc/init.d/sshd查看脚本文件

[[email protected] ~]# cat /etc/init.d/sshd

#!/bin/bash    #指定脚本解释器的类型

#

# sshd        Start up the OpenSSH server daemon

#

# chkconfig: 2345 55 25        

#2345表示执行chkconfig命令时的默认修改运行级别

#55表示启动顺序

#25表示关闭顺序

# description: SSH is a protocol for secure remote shell access. \

#              This service starts up the OpenSSH server daemon.

#

# processname: sshd

2、自定义开机启动脚本的步骤

基本思路:编写脚本文件,然后为脚本文件添加可执行权限,最后将脚本文件添加到开机启动的服务中去即可

[[email protected] ~]# touch /etc/init.d/ceshijiaoben             #创建脚本文件

[[email protected] ~]# vim /etc/init.d/ceshijiaoben                #编辑脚本文件

#!/bin/bash

#chkconfig: 2345 55 25

echo 开机报时`date` >/tmp/a.txt

[[email protected] ~]# chmod +x /etc/init.d/ceshijiaoben         #为脚本文件添加执行权限

[[email protected] ~]# ll /etc/init.d/ceshijiaoben                 #查看脚本文件的权限

-rwxr-xr-x 1 root root 60 Apr  8 16:40 /etc/init.d/ceshijiaoben

[[email protected] ~]# chkconfig --add /etc/init.d/ceshijiaoben     #将脚本文件添加到开机启动服务中

[[email protected] ~]# reboot                                #重启

Broadcast message from [email protected]

    (/dev/pts/0) at 16:43 ...

The system is going down for reboot NOW!

[[email protected] ~]# Connection closing...Socket close.

Connection closed by foreign host.

Disconnected from remote host(52113) at 16:44:28.

Type `help' to learn how to use Xshell prompt.

[x:\~]$

Connecting to 10.22.66.132:52113...

Connection established.

To escape to local shell, press Ctrl+Alt+].

Last login: Sun Apr  8 16:42:37 2018 from 10.22.66.1

[[email protected] ~]# chkconfig --list|grep ceshijiaoben    #检查脚本文件的运行级别

ceshijiaoben       0:off    1:off    2:on    3:on    4:on    5:on    6:off

[[email protected] ~]# cat /tmp/a.txt                     #检查脚本文件重定向的文件是否成功

开机报时Sun Apr 8 16:51:21 CST 2018