Example#
Suppose I want my Linux device to automatically run two commands at startup:
cd /test
nohup python3 -m http.server 6666
โtips: Why use nohup? Because nohup is a silent command that does not output to the terminal, the log will be stored in the /test/nohup.out file.
Operation#
.sh File#
Create a file named test.sh, enter the following combined code:
#!/bin/bash
(cd /test && nohup python3 -m http.server 6666) &
Here, use the && operator to ensure that the nohup command is only executed after the cd command is successfully executed. The & symbol is used to run the nohup python3 -m http.server 6666 command in the background.
.service File#
Create a file named test.service in the /etc/systemd/system directory, type:
[Unit]
Description=HTTP Server
[Service]
ExecStart=/test/test.sh
Restart=always
[Install]
WantedBy=default.target
Use the following commands to enable and start the service:
sudo systemctl enable test.service
sudo systemctl start test.service
Done, the nohup python3 -m http.server 6666 command will automatically run when Linux starts.
Stop the service:
sudo systemctl stop http_server.service
Disable the service:
sudo systemctl disable http_server.service