1

I have a shell script contain loop like this:

while true
do
  if ... ; then
    ...
  else
    ...
    break
  fi
done

I want this script to run backend while OS start. I have try to add this script into /etc/rc.d/local.rc as startup script. But OS start too long, and after OS start up, this script did not exist.

So how to add this script into backend while OS start up? And I need this script also could be start up by hand in backend. Thank you~

2 Answers2

3

To run a script on startup, you should start it from

/etc/cron.d/myrebootscript

with the content

@reboot <user> <command>

example:

@reboot joe /usr/local/bin/myscript

The script will be executed at an unpredictable time during startup. If for instance the script should wait for the network to be started, a loop should be added to /usr/local/bin/myscript:

#! /bin/bash
# wait for 10.1.2.3 is pong'ing
while ! ping -c1 -W1 10.1.2.3 > /dev/null ; do
  sleep 1
done
do_my_command_here

/etc/rc.local is deprecated nowadays.

hschou
  • 2,910
  • 13
  • 15
  • 1
    When does cron run the script? After all the services or while? Because OP wanted the script to run while the OS start's up. +1 for the answer though, I love this cron option. – Hunter.S.Thompson Nov 07 '17 at 09:03
  • Just how "unpredictable" is the timing? Also, how can it decide whether or not to wait for the network? – SDsolar May 05 '18 at 02:26
  • To find out about the timing, put a line in your script with /usr/bin/logger My script startet and look for that message in /var/log/syslog afterwards. To avoid waiting for the network just skip the while block. – hschou May 06 '18 at 07:43
  • @Hunter.S.Thompson The cron script will start after the cron service has started. – hschou May 06 '18 at 07:45
0

Include the script in /etc/rc.d/rc.local file so it will execute once all init scripts are executed.

Another option we can add path in .bash_profile