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

如何在Bash脚本中加载子目录下多个脚本并调用其函数?

Why Only d1.sh Is Loaded & How to Fix It

Root Cause

The source (or .) builtin in Bash only accepts one filename as its primary argument. When you run source ./deep/*, Bash expands the wildcard to the list of files in the deep directory (e.g., ./deep/d1.sh ./deep/d2.sh), but source will only process the first file in that expanded list. That's why you only see the output from d1.sh and can't access the test function from d2.sh—it was never sourced.

Correct Approach: Loop Through Each Script

To load all scripts in the deep directory, you need to iterate over each file and source them individually. Here's how to update your run.sh:

#!/bin/bash
# Source all .sh scripts in the deep directory
for script in ./deep/*.sh; do
    # Check if the file exists (prevents errors if no .sh files are present)
    if [ -f "$script" ]; then
        source "$script"
    fi
done

# Now you can call the test function from d2.sh
test

Key Notes:

  • Using ./deep/*.sh ensures we only target shell script files, avoiding any non-script files that might be in the directory.
  • The [ -f "$script" ] check prevents errors if there are no .sh files in the directory (Bash would otherwise expand the wildcard to the literal string ./deep/*.sh).
  • The scripts will be sourced in lexical order (so d1.sh comes before d2.sh), which matches your original intent.

When you run bash run.sh now, you'll see the expected output:

d1 is loaded
d2 is loaded
test passed!

内容的提问来源于stack exchange,提问作者s-kaczmarek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:31:48