How do you execute a SHELL script in multiple dire

2020-02-13 05:13发布

问题:

If I have the following file directory

/home/aero/airplane/case1
/home/aero/airplane/case2
..
/home/aero/airplane/casex (you get the point there could be many cases)

I have a shell script called runscript.sh (at the same level of all the cases) that performs some simple commands. I don't want to "cd" into each directory manually to then run the shell script. Is there a way to execute the shell script on all case directories that contains the name "case" by typing something along the lines of:

runscript.sh /case*

I know I can generate another script that could do this but I'm wondering if there's a way to run a script on multiple directories using a simple command?

Your help on this is much appreciated!

回答1:

When you want to execute runscript.sh in the subdir itself, you want to find something for avoiding the lines

cd case1 && runscript.sh && cd ..
cd case2 && runscript.sh && cd ..

Here runscript.sh can return false and your cd .. can get you to wrong places.
You can avoid this by running everything in a subshell.
Test this with the runscript.sh script replaced by pwd.

(cd case1 && pwd)
(cd case2 && pwd)

Now wrap this up in a command finding all dir's starting with "case".

find case* -maxdepth 0 -type d -exec bash -c 'cd "{}"; pwd' \;

When you are happy with the result, fill in your script

find case* -maxdepth 0 -type d -exec bash -c 'cd "{}"; ../runscript.sh' \;


回答2:

Try using a for loop. In this example you need to run the command from /home/aero/airplane/.

for dir in `ls -ad case*`; do runscript.sh $dir/; done
  • ls -ad case*: list only directories starting with "case".


标签: shell