1 Step by step

  1. Put all your executing code in a separate text file with an arbitrary name such as​​foo.sh​​ and save it in an arbitrary place like ​​/home/tzx/go/src/foo/foo.sh​​.
  2. Add​​#!/bin/sh​​ as first line of your code.
    Like the following of​​foo.sh​
#!/bin/sh
cd /home/tzx/go/src/foo
go build
nohup ./foo >/dev/null 2>&1 &

And do ​​$ chmod 755 foo.sh​

  1. Try executing your​​foo.sh​​​ by​​$ ./foo.sh​​ to check there are no errors at all.
  2. Provide your​​/etc/rc.local​​ script withfull pathand name of your created script after the sh command like
# Root user [Not recommend]
#sh '/home/tzx/go/src/foo/foo.sh'
# Normal user
/bin/su - tzx -c "sh /home/tzx/go/src/foo/foo.sh"
  1. Remember to put the above line before the last line of code​​exit 0​​ at the end of the ​​/etc/rc.local​​ script like
#!/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.

# Root user [Not recommend]
#sh '/home/tzx/go/src/foo/foo.sh'

# Normal user
/bin/su - tzx -c "sh /home/tzx/go/src/foo/foo.sh"

exit 0
  1. [Optional] Check first line of /etc/rc.local to be ​​#!/bin/sh -e​
  2. [Optional] Make your ​​/etc/rc.local​​ executable in case it is not already executable by
$ sudo chown root /etc/rc.local
$ sudo chmod 755 /etc/rc.local
  1. Check everything works fine by executing​​$ sudo /etc/init.d/rc.local start​​.
  2. Test restart your system by​​$ sudo reboot​​.

2 Reference