0

Hi everyone and thank you for your time. I'm very new to bash scripting so i'm not the slightest bit aware of how to approach this problem. I have a directory that contains a lot of sub-directories like:

test-01
test-02
test-03
test-04
test-05
and so on..

I was wondering could someone show me how to cd into each directory one at a time, execute some commands, exit the directory and repeat the process with the next directory.

1
  • No need to cd in a directory to execute a command. You must tell more. Commented Jul 2, 2019 at 16:29

2 Answers 2

1

Could be a good time to learn pushd and popd! I like using these instead of cd in scripts, that way if something breaks, it hangs onto context a little better. Also, when it runs successfully, you're right back in your original directory.

Note: A stumbling block you might encounter is building your "list" of directories. We can create this "list" by utilizing bash's pattern matching capabilities. For example, if we know that ALL the directories you'd like on your 'list' need to start with the pattern "test", we can simply append "test*" to your current working directory.

Let's say my cwd is /home/ben and there are 5 dirs here [test1,test2,test3,test4,test5] To create a full list (and simultaneously loop through that list), we can just do this:

for dir in /home/ben/test*; do cd ${dir}; pwd; done # Visit each dir in our little list

output:

/home/ben/test1 /home/ben/test2 /home/ben/test3 /home/ben/test4 /home/ben/test5

This little snippet does the same thing, but uses pushd and popd to traverse the list of test* dirs.

for dir in /{your_path_prefix_here}/test*; do
  pushd ${dir} >/dev/null # We've arrived in this directory, and it's now in your stack. (hide the output, which displays your directory stack)

  ### Run whatever command you want, and then...  

  popd >/dev/null # Now you're right back where you were!
done
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic. Super glad I could help!
0

You can do something like this:

for dir in /path/to/mydir/test-*/
do
  cd $dir
  // exec your command here
done

In this case you use the shell's globbing features to match all test-directories and loop using a bash loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.