Run script once at startup

Hi,
This is possibly an easy thing to do but I’m fairly new to Linux so I’m not quite sure.

I need to run a shell script once when the system starts. How do I get that to happen?

I initially thought of using cron, but that seems to be for repeated tasks. So I then looked into using an entry in /etc/init.d/rc.5 (as an example) but those seem to be for ‘services’ which would seem to be over the top for what I want.

Is there a more commonly used option or is one of these the best way forward ?

I can’t put this into any logon processing for a user because the system in question is a server and hence on most times no user will logon.

Many thanks,
Dave

Hi, three possibilities;

a. Add your command to /etc/rc.local - this is the easiest
b. Write your own init script and install in init.d, then link to /etc/init.d/rc.d (on ubuntu, use “update-rc.d”)
c. Add to cron, with “crontab -e” (as root) then add “@reboot /” at the top, no time information

(/etc/rc.local might be /etc/init.d/rc.local depending on your distro)

It would help if you said which Linux distribution/version :wink:

Hi Mark,

Many thanks for that, I used the “cron @reboot” option and it works a treat! My distro is SUSE v10.

Another question if I may.

In a script, how do I set the ‘current directory’ to be the one where the script is located? The situation I’ve got is as follows:

  • I use cron to run scripts as required
  • near the start of most of these I have a “cd” command to set the current directory. This allows my code which accesses files in the script directory to work fine.
  • as soon as I move the scripts or send them to a different machine (where I have no control over the directory names) then this is one thing that has to be changed.
  • I’m assuming that there will be a commend (or two) that I can use to “set current directory to thw one containing the script file”.

All ideas gratefully received.

Cheers,
Dave

Wouldn’t

cd ./

do the trick ?

Don’t know, I’ll try it.

Thanks.

In a script, how do I set the 'current directory' to be the one where the script is located?

How about BASH_SOURCE[0]?
You could try (untested):

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"