How do I autostart a tmux bash script as a startup service in Ubuntu?

243 views Asked by At

I used to run a TShock server on a Raspberry Pi 4. I've recently gotten more powerful hardware, an Intel "Skull Canyon" NUC6i7KYK with a new installation of Ubuntu 23.10, and I'm trying to replicate my server setup with systemd instead of init.d and rc.local like I did on the Pi.

I'm looking for the best method to start the server inside tmux during system startup, as my current strategy of starting it as a bash script run via a service might be overcomplicating things. Here's my current approach:

I have a shell script here that runs the server:

/home/terraria/start-server.sh

#!/bin/bash
/home/kokonoe/terraria/tshock/TShock.Server -config /home/kokonoe/terraria/serverconfig

Another shell script that starts the server in a tmux session, split-screened with htop:

/home/terraria/autostart.sh

#!/bin/bash
export DOTNET_ROOT=/home/kokonoe/terraria/tshock/dotnet  # this is normally set in ~/.bashrc, but systemctl doesn't seem to see it there.
tmux new -s tshock -d "/bin/bash /home/kokonoe/terraria/start-server.sh"
tmux split-window -h "htop"
tmux last-pane

These two scripts work well in a terminal session and will start the server as expected. However, I'm struggling with writing a systemctl service to start the server on startup. I have a .system file here:

/etc/systemd/system/terraria-autostart.service

[Unit]
Description=Runs TShock in a tmux session.

[Service]
ExecStart=/bin/bash /home/kokonoe/terraria/autostart.sh
User=kokonoe
Type=oneshot
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

I ran sudo systemctl daemon-reload and then sudo systemctl start terraria-autostart. What I expect to happen is for a tmux session to get created, split horizontally, with tshock on the left and htop on the right, like what happens when I run ~/terraria/autostart.sh, but instead, I only see htop and nothing else, so the server script exited and closed its pane.

I suspect some weirdness with environment variables or PATH or something, but I'm not sure where to start poking, or if a service is even the best way to implement a start-up script. Thanks for the look!

1

There are 1 answers

1
Kokonoe On

After some tinkering with setting environment variables, such as sourcing .profile and .bashrc, running it via services wasn't panning out. However, running the script as a cron job via @reboot eventually worked as expected. I have no idea how the two differ in terms of their environments, but mayhaps this can help a future gamer!