如何分批执行/home目录下各子文件夹中foo文件的source命令
Batch Sourcing
/home/*/foo Files in Groups of 20 Hey there! Let's fix that batch sourcing issue for you. Your original script has a small syntax error (you meant source "$file" instead of source */foo), but the bigger goal is splitting the 80 files into batches of 20. Here are a couple of straightforward ways to do this:
Method 1: Using Bash Arrays (Clean & Flexible)
This approach stores all target files in an array first, then processes them in chunks using array slicing. It's easy to adjust the batch size and adds error checking to skip missing files.
# Store all /home/*/foo files in an array files=(/home/*/foo) # Set your desired batch size batch_size=20 # Loop through the array in batches for ((index=0; index<${#files[@]}; index+=batch_size)); do # Extract the current batch of files current_batch=("${files[@]:index:batch_size}") echo "=== Starting batch $((index/batch_size + 1)): Processing ${#current_batch[@]} files ===" # Source each file in the batch for file in "${current_batch[@]}"; do if [[ -f "$file" ]]; then source "$file" echo "Successfully sourced: $file" else echo "Warning: $file does not exist, skipping" fi done # Optional: Pause between batches to verify progress if (( index + batch_size < ${#files[@]} )); then read -p "Press Enter to proceed to the next batch..." fi done echo "✅ All ${#files[@]} files processed!"
Why this works:
${#files[@]}gives the total number of files in the array${files[@]:index:batch_size}slices the array to getbatch_sizeelements starting atindex- The optional pause lets you confirm each batch completes before moving on (remove the
readline if you want fully automatic processing)
Method 2: Using a Counter (Simple & Iterative)
If you prefer a more linear approach without arrays, use a counter to track how many files you've processed and pause every 20:
count=0 batch_size=20 for file in /home/*/foo; do if [[ -f "$file" ]]; then source "$file" echo "Sourced: $file" ((count++)) # Pause after every full batch (except the last one) if (( count % batch_size == 0 )) && (( count < 80 )); then read -p "Processed $count files. Press Enter to continue..." fi else echo "Skipping missing file: $file" fi done echo "✅ Done! Processed $count total files."
Key Notes:
- Important: When you run this script, make sure to execute it in your current shell session using
source ./your_script.shor. ./your_script.sh—if you run it withbash ./your_script.sh, the variables/settings from the sourcedfoofiles won't persist in your main shell. - Always add a check for file existence (
[[ -f "$file" ]]) to avoid errors if any/home/*/foopath doesn't exist.
内容的提问来源于stack exchange,提问作者machinecat
相关产品推荐
相关产品推荐

