如何在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/*.shensures 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.shfiles 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.shcomes befored2.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
相关产品推荐
相关产品推荐

