如何通过tcsh脚本并行运行多目录任务?
Extending Your tcsh Script for Parallel Multi-Directory Processing
Hey there! Let's fix up your script to handle directories a, b, and c with identical logic, and run all three tasks in parallel. Here's the revised version:
#!/bin/tcsh -f # Define a reusable function to handle a single directory process_dir() { set target_dir = $1 set original_pwd = $PWD # Create directory, enter it, and set up symlink if it doesn't exist if (! -d $target_dir) then mkdir $target_dir cd $target_dir ln -sfn temp.txt endif # Navigate to the target directory and execute the job cd $original_pwd/$target_dir job << END # some tool specific settings END # Return to the original working directory cd $original_pwd } # Loop through a, b, c and run each task in the background (parallel) foreach dir (a b c) process_dir $dir & end # Wait for all background tasks to finish before exiting wait
Key Changes & Explanations:
- Reusable Function: We wrapped the directory setup and job execution into a
process_dirfunction. This lets us reuse the exact same logic fora,b, andcwithout duplicating code. - Parallel Execution: Adding
&at the end of theprocess_dircall sends each task to run in the background. This means all three jobs will execute simultaneously instead of one after another. - Fix Directory Check: The original script had an invalid check
if (!a)— we replaced it with! -d $target_dirto properly test if the directory exists. - Wait for Completion: The final
waitcommand ensures the main script doesn't exit until all background jobs have finished running. This is crucial if you need the script to only exit once all work is done.
内容的提问来源于stack exchange,提问作者RMK
相关产品推荐
相关产品推荐

