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

Shell脚本执行相对路径子脚本报错,如何保留相对路径实现调用?

Solution: Fix Relative Path Sourcing Across Directories

Absolutely, this is totally feasible—you just need to adjust how your scripts resolve relative paths, since the issue boils down to how shells interpret ./ references.

Why the Error Happens

When you run a.sh, your current working directory (CWD) is wherever you executed the script from (e.g., your project's root folder). The source ./c.sh line in b.sh looks for c.sh relative to this CWD, not relative to b.sh's actual location inside the stuff folder. That's why you get the "No such file or directory" error—your shell is checking the root directory for c.sh, not stuff.

The Fix: Anchor Paths to Script Locations

The solution is to make each script reference its own directory first, then use that to build the path to the script it needs to source. This keeps your relative path logic intact while ensuring the script finds its dependencies no matter where it's run from.

Update a.sh:

# a.sh
# Get the absolute path of the directory where this script lives
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
# Source b.sh using a path relative to a.sh's directory
source "$SCRIPT_DIR/stuff/b.sh"

Update b.sh:

# b.sh
# Get the absolute path of the directory where this script lives
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
# Source c.sh using a path relative to b.sh's directory
source "$SCRIPT_DIR/c.sh"

How This Works

Let's break down the key parts:

  • ${BASH_SOURCE[0]} returns the path to the current script (whether you ran it with a relative or absolute path).
  • dirname "${BASH_SOURCE[0]}" extracts the directory portion of that script path.
  • cd "$(dirname ...)" &>/dev/null && pwd silently changes into that directory and prints its absolute path—this gives us a consistent, fixed location for the script's home directory, regardless of your working directory when you run the script.
  • Using $SCRIPT_DIR to build the source path ensures we're referencing files relative to the script's actual location, not your variable working directory.

With these changes, you can run a.sh from any directory, and it will correctly find b.sh and c.sh using relative path logic tied to each script's folder.

内容的提问来源于stack exchange,提问作者Nick Ginanto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:49:07