一条命令将Linux应用安装为systemd服务运行
脚本install-app-as-service.sh
:
#!/bin/bash
# 检查参数是否正确
if [ $# -ne 1 ]; then
echo "Usage: $0 <target-directory or executable-file>"
exit 1
fi
TARGET="$1"
# 根据输入参数的类型选择操作模式
if [ -f "$TARGET" ] && [ -x "$TARGET" ]; then
# 单个可执行文件模式
echo "Single executable file detected. Installing as a service."
# 获取基本信息
executable="$TARGET"
service_name=$(basename "$executable").service
service_path="/etc/systemd/system/$service_name"
exec_path=$(realpath "$executable")
work_dir=$(dirname "$exec_path")
echo "Installing $exec_path as systemd service: $service_name"
# 生成服务文件内容(包含路径转义)
service_content="[Unit]
Description=Service for $(basename "$executable")
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=$work_dir
ExecStart=\"$exec_path\"
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target"
# 写入系统服务文件
echo "$service_content" | sudo tee "$service_path" > /dev/null
# 设置文件权限
sudo chmod 644 "$service_path"
# 重新加载systemd并启用服务
sudo systemctl daemon-reload
sudo systemctl enable "$service_name"
sudo systemctl start "$service_name"
echo "Successfully installed and started $service_name"
elif [ -d "$TARGET" ]; then
# 目录模式,与原来功能一致
echo "Directory mode: Installing all executables in directory as services."
# 查找所有可执行文件并处理
find "$TARGET" -maxdepth 1 -type f -executable | while read -r executable; do
# 获取基本信息
service_name=$(basename "$executable").service
service_path="/etc/systemd/system/$service_name"
exec_path=$(realpath "$executable")
work_dir=$(dirname "$exec_path")
echo "Installing $exec_path as systemd service: $service_name"
# 生成服务文件内容(包含路径转义)
service_content="[Unit]
Description=Service for $(basename "$executable")
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=$work_dir
ExecStart=\"$exec_path\"
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target"
# 写入系统服务文件
echo "$service_content" | sudo tee "$service_path" > /dev/null
# 设置文件权限
sudo chmod 644 "$service_path"
# 重新加载systemd并启用服务
sudo systemctl daemon-reload
sudo systemctl enable "$service_name"
sudo systemctl start "$service_name"
echo "Successfully installed and started $service_name"
done
echo "All executable services installed from $TARGET"
else
echo "Error: '$TARGET' is neither a valid directory nor an executable file."
exit 1
fi
使用:
sudo install-app-as-service.sh path-to-the-app(指向单个可执行程序)
sudo install-app-as-service.sh path-to-the-dir(指向可执行程序上级目录,支持多个批量安装)