You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

systemd服务执行Shell脚本时cd命令无法切换目录的问题求助

systemd服务执行Shell脚本时cd命令无法切换目录的问题求助

我在Debian系统上有一个运行Sphinx搜索的Shell脚本,直接在终端里用下面的命令运行完全正常:

sh /home/myuser/sphinx/run_sphinx.sh

脚本run_sphinx.sh的内容是这样的:

#!/bin/bash
cd bin/ || exit
./searchd -c ../../application/engine/config/sphinx_config_files/sphinx.conf

为了让服务器重启后自动运行这个脚本,我创建了一个systemd服务,配置如下:

[Unit]
Description=My Description

[Service]
User=myuser
WorkingDirectory=/home/myuser/
ExecStart=sh /home/myuser/sphinx/run_sphinx.sh
# optional items below
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

但当我执行sudo systemctl start run-sphinx-on-startup.service启动服务时,却报错了:

/home/myuser/sphinx/run_sphinx.sh: 2: cd: can't cd to bin/
systemd[1]: run-sphinx-on-startup.service: Main process exited, code=exited, status=2/INVALIDARGUMENT
systemd[1]: run-sphinx-on-startup.service: Failed with result 'exit-code'.

为什么通过systemd服务运行脚本时,cd命令无法识别目标目录呢?有没有大佬能帮忙解决这个问题?谢谢!


问题原因分析

你遇到的问题核心是相对路径的工作目录差异:

  • 当你在终端运行脚本时,终端的当前工作目录加上脚本里的bin/相对路径,刚好能指向正确的/home/myuser/sphinx/bin/目录;
  • 但systemd服务里你设置了WorkingDirectory=/home/myuser/,脚本运行时的当前工作目录变成了/home/myuser/,这时候执行cd bin/会尝试切换到/home/myuser/bin/——这个目录根本不存在,所以就触发了报错。

解决方法(任选其一即可)

方法1:修改脚本为绝对路径

把脚本里的相对路径全部改成绝对路径,这样不管当前工作目录在哪都能正确找到目标:

#!/bin/bash
cd /home/myuser/sphinx/bin/ || exit
./searchd -c /home/myuser/application/engine/config/sphinx_config_files/sphinx.conf

方法2:修改systemd服务的工作目录

把systemd配置里的WorkingDirectory改成脚本所在的目录,让脚本里的相对路径基于这个目录生效:

[Service]
User=myuser
WorkingDirectory=/home/myuser/sphinx/  # 修改这里
ExecStart=sh /home/myuser/sphinx/run_sphinx.sh
Restart=always
RestartSec=3

方法3:让脚本自动定位自身所在目录

这种方式更灵活,脚本不管被放在哪个路径下都能正确找到相关文件,适合需要迁移脚本的场景:

#!/bin/bash
# 获取脚本自身所在的绝对目录
SCRIPT_DIR=$(dirname "$(realpath "$0")")
# 切换到bin目录
cd "$SCRIPT_DIR/bin/" || exit
# 使用绝对路径指向配置文件
./searchd -c "$SCRIPT_DIR/../../application/engine/config/sphinx_config_files/sphinx.conf"

备注:内容来源于stack exchange,提问作者Dev Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 13:23:06