Startup script; runs commands as certain user + screen
FILE: /etc/init.d/myscript
#!/bin/bash
RETVAL=0
# To start the server
start() {
echo -n "Starting server: "
su user -c "/home/user/dir/startserver.bash"
RETVAL=0
}
# To stop the server
stop() {
echo -n "Stopping server: "
su user -c "/home/user/dir/stopserver.bash"
RETVAL=0
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
su user -c "/home/user/dir/statusscript.bash"
RETVAL=0
;;
*)
echo "Usage: server {start|stop|restart|status}"
RETVAL=1
esac
exit
To automatically load
$ sudo chmod +x /etc/init.d/myscript
$ sudo update-rc.d myscript defaults
Will this automatically run the script as root, but will execute the commands as user without password prompt?
Basically, I am trying to automatically start a server, but don't want it to run as root, but as a user.
Still reading through the manual for screen, so not sure yet if I can run a script at startup which will create a screen as a specified user, then start the server as that specified user, then detach the screen.
The server runs in the foreground where I can input commands.
So my goal is to start the server in a new screen on boot, so when I log in I can switch to that screen.
Any input and help would be appreciated.
Edit: Added "s after -c
3 Replies
@reboot screen -d -m command-name
> -d -m Start screen in "detached" mode. This creates a new session but doesn’t attach to
it. This is useful for system startup scripts.
That @reboot may be version-specific, if it doesn't work then create a script in /etc/rcX.d
@phvt:
Edit: Need more coffee. You even used sudo
;)
And I needed some much needed sleep; forgot to put the command in quotes after using su user -c. (no wonder it wouldn't quite work)
@Alucard:
In the user's crontab:
@reboot screen -d -m command-name
> -d -m Start screen in "detached" mode. This creates a new session but doesn’t attach toit. This is useful for system startup scripts.
That @reboot may be version-specific, if it doesn't work then create a script in /etc/rcX.d
perfect that is what i needed; used
screen -d -m -S name su user -c "/home/user/dir/startserver.bash"
Now I just have one more question, when I start the server it is in the foreground waiting for commands; however, there are a few more lines in the script that I need executed, but they will only execute after the server is stopped (gets out of the foreground).
The rest of the script will run if I start the server in the background by using "command &", but this kills the point of running the server in a separate screen.
Basically, after the server starts i pull the pid and write it to a file, then i use that file to check the status and stop the server. So that part of the script needs to be run after the server starts.
Can't use bg/fg b/c I don't want to stop the process.
What would you think is the best way to do this?