Creating startup program on Raspberry Pi by rc.local

rc.local execute once after normal system service (including networking) single-user mode and before multi-user runlevel (GUI and login).

As rc.local runs before X starts, so please do not includes settings with graphical interface. For more information about runlevel, and rc.local, you may visit https://learn.sparkfun.com/tutorials/how-to-run-a-raspberry-pi-program-on-startup/method-1-rclocal

sudo nano /etc/rc.local

Put your script before exit 0. Here is an example of replacing in file text and copying files. The ampersand & at the end of the lines indicates the rc.local script does not wait for that script ends before executing the next line, which is important when you have an infinite loop such as blinky.

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi


sudo sed -i 's/Old string to be replaced/new string to be replaced/g' /home/pi/textfile.txt &

sudo cp -r /home/pi/somephoto/* /home/pi/destinationdir/ &


exit 0

sed is a streamlined editor and could edit the file without opening a text editor. the option -i edit the textfile.txt itself, or else, changes will print to the console only. The s/ stand for substitute and /g for global replacement. Man sed for more information.

Reminders

Someone suggested setting up the script in bash.rc, which runs every time an interactive shell is prompted such as logging in to the shell. Usually Raspberry pi will enable auto login so most of the case bash.rc runs after boot up.

One thought on “Creating startup program on Raspberry Pi by rc.local”

Leave a Reply

Your email address will not be published. Required fields are marked *