Execute script on Linux startup/shutdown

Source: http://blog.chinaunix.net/uid-21209618-id-370787.html

 

Execute the corresponding command in .login, or write the command in .bashrc (with tcsh shell, in .tcshrc). No, .login is executed when the user logs in, the user may not need to log in locally, or multiple users log in remotely and log in multiple times; while .tcshrc is executed when the shell starts, and the user will generally open it multiple times after logging in. shell, so that the command or program is executed multiple times.

Linux boot sequence:

1. BIOS self-test

2. Run the system kernel and detect the hardware

3. The first process of running the system, init

4. init reads the information in the system boot configuration file /etc/inittab to initialize

/etc/rc.d/rc.sysinit------ system initialization script

/etc/rc.d/rcX.d/[KS]*------Configure services according to runlevel

/etc/rc.d/rc.local---------Perform local special configuration

Other---------Special services for different run levels

Linux starts and runs the init program to start the initialization of related programs. A concept related to startup is the run level. The run level is the current operating level of the operating system. In different run levels, the startup program belonging to the run level can be defined, and the system run level It can be specified in the /etc/inittab file, and the running program related to the running level is linked from the source /etc/rc.d/init.d to the destination /etc/rcX.d, where X is the default running level of the system, so, The default startup script is placed under /etc/rc.d/init.d.

Case, task runs mm on startup:

method:

1. Create a self-starting script /etc/rc.d/init.d/mm with the following contents:

#!/bin/bash

/usr/local/bin/* (Note: replace this content with the command you want to execute)

Set the file's attribute to executable:

#chmod +x /etc/rc.d/init.d/mm

2. 查看计算机运行级别,在文件/etc/inittab里看到id:3:initdefault:,则此系统运行级别为3。

3. 到/etc/rc3.d目录下,把你要执行的可执行文件做一个软连接,而且在命名的时候要以大写S字母开头,S之后的数字大小代表执行顺序的先后,数字越大越靠后执行。

#ln -s /etc/rc.d/init.d/mm /etc/rc3.d/S100mm

#ln -s /etc/rc.d/init.d/mm /etc/rc0.d/K20mm

关机执行脚本:

 1. vi /etc/init.d/mm 

     #!/bin/bash

     ls >/dev/null 2>&1  (此处把ls替换为你自己的内容)

  注意:此处的顺序不能更改,否则达不到想要的效果。此时先将标准输出重定向到 /dev/null,然后将标准错误重定向到标准输出,由于标准输出已经重定向到了/dev/null,因此标准错误也会重定向到/dev/null。

 2. chmod +x /etc/init.d/mm

 3. ln -s /etc/init.d/mm  /etc/rc6.d/K01mm /var/lock/subsys/

 4. 当你在关机时一切在悄无声息的进行着。

注:(1)本人在实验时,做关机运行脚本不成功解决方法。是在 /var/lock/subsys/中建立相同的文件mm,或拷贝或者直接软链接过来 ln -s /etc/init.d/mm /var/lock/subsys/   。

    (2)若在字符界面下只设置开机启动,只在rc3.d目录下链接S100filename便可。
           如:ln -s /etc/init.d/filename  /etc/rc3.d/S100filename

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326925761&siteId=291194637