LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to get into multiple directories in Linux (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-get-into-multiple-directories-in-linux-891713/)

xibeimunan 07-14-2011 09:19 AM

How to get into multiple directories in Linux
 
Hey everyone,
I have a directory list, say, test{0..9}. Now I'd like to get into each one and run some commands and then go to the next directory. Could anyone help me write a simple script to do that? Thanks in advance.

Nan

markush 07-14-2011 10:05 AM

Hello xibeimunan,
Code:

for i in {1..9}; do cd test$i; yourcommandhere; cd ..; done
Markus

David the H. 07-14-2011 10:07 AM

Code:

for dir in test{0..9} ; do
  (
    cd "$dir"
    <run commands>
  )
done

Putting the commands inside (...) makes them run inside a subshell. this means that the the cd only affects that subshell environment, and you're back to where you started when it exits, ready for the next iteration.

However this won't do if you need to set any variables that are to be read outside of the loop. So you could also do this:

Code:

for dir in test{0..9} ; do
    cd "$dir"
    <run commands>
    cd -
done

Where the final cd command returns you to the previous directory.

xibeimunan 07-14-2011 10:55 AM

Thanks a lot for your comments!


All times are GMT -5. The time now is 08:52 PM.