linux - [Solved-5 Solutions] How to run a shell script at startup in Linux ? - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

How to run a shell script at startup in Linux ?

Linux - Solution 1:

In the file you put in /etc/init.d/ you have to set it executable with:

chmod +x /etc/init.d/start_my_app
click below button to copy the code. By - Linux tutorial - team

if this does not run you have to create a symlink to /etc/rc.d/

ln -s /etc/init.d/start_my_app /etc/rc.d/
click below button to copy the code. By - Linux tutorial - team

Please note that on latest Debian, this will not work as your script. To provide the following actions: start, stop, restart, force-reload, and status.

As a note, you should put the absolute path of your script instead of a relative one, it may solves unexpected issues:

/var/myscripts/start_my_app
click below button to copy the code. By - Linux tutorial - team

And don't forget to add on top of that file:

#!/bin/sh
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 2:

Set a crontab for this

#crontab -e
@reboot  /home/user/test.sh
click below button to copy the code. By - Linux tutorial - team

after every startup it will run the test script.

Linux - Solution 3:

A simple approach is to add a line in /etc/rc.local :

/PATH/TO/MY_APP &
click below button to copy the code. By - Linux tutorial - team

or if you want to run the command as root :

su - USER_FOOBAR -c /PATH/TO/MY_APP &
click below button to copy the code. By - Linux tutorial - team

If you want a full init script, you can use the following template:

cp /etc/init.d/skeleton /etc/init.d/your_app
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 4:

Put your script in /etc/init.d, owned by root and executable. At the top of the script, you can give a directive for chkconfig. Example, the following script is used to start a java application as user oracle.

The name of the script is /etc/init.d/apex

#!/bin/bash
# chkconfig: 345 99 10
# description: auto start apex listener
#
case "$1" in
 'start')
   su - oracle -c "cd /opt/apex ; java -jar apex.war > logs/apex.log 2>logs/apex_error.log &";;
 'stop')
   echo "put something to shutdown or kill the process here";;
esac
click below button to copy the code. By - Linux tutorial - team

The script must run at levels 3, 4 and 5 and the priority for start/stop is 99 and 10.

As user root you can use chkconfig to enable or disable the script at startup,

chkconfig --list apex
chkconfig --add apex
click below button to copy the code. By - Linux tutorial - team

You can use service start/stop apex

Linux - Solution 5:

Another option is to have an @reboot command in your crontab.

Not every version of cron supports this, but if your instance is based on the Amazon Linux AMI then it will work.


Related Searches to - linux - linux tutorial - How to run a shell script at startup in Linux ?