foreach folder

Hi,

I'm having a small issue here and I can't get it to work. I'm programming a script for bash and I need to do something to all the folder in a directory. So I'm in the directory and I want to use the foreach statement but I dont know how to reference all the folders of that directory. To make things simplistic here's my code:

foreach instance (.)
cd instance
mkdir test
end

basically for each folder in that directory, I want to cd into it and create a folder called test. Any ideas?

Something like this:

for file in *; do
   if [ -d $file ]; then
      cd $file; mkdir test
   fi
done

-EDIT
You can skip the testing for directory as well. 'cd' won't work on anything except directories (but there might be links that point to directories and you'd end up creating "test" where you don't want to).

A small correction blowtorch.

for file in *; do
   if [ -d $file ]; then
      mkdir $file/test; 
   fi
done

Since you had issued a cd command it would create the sub-dir only for the first directory. So the result would not be as expected.

Your main problem here was not logic, but that you were using the syntax from the wrong shell. This is csh syntax.

Thanks guys. So basically there is no foreach command in bash?

No, there is not.

The equivalent is

for instance in * ; do
...
done

Hi, I had a question about the cd thing, how come it doesn't work? I'm modifying the code to go into certain subfolders in each folder and then execute a command so I wasn't sure how to do that. Basically I'm trying to do something like this now...

current directory:
a b c

Inside of each directory there is a file here (using a as an example):
a/test/folder/script.sh

Sorry for the generic names. Now what I want my script to do is access that script.sh in each folder and run it. I was gonna do the for statement and then cd into that path and then do an execute command but I guess it's not that simple. Any ideas? thanks!

You can try like

for file in *; do
   if [ -d $file ]; then
      ./$file/test/folder/script.sh; 
   fi
done

or if you are particular to go into the dir and execute the script then try like this

scriptHome=$(pwd)   # Assuming that you are running from the path where a b c are present
for file in *; do
   if [ -d $file ]; then
      cd $file/test/folder;
      ./script.sh
   fi
   cd $scriptHome
done

Again assuming that the tree structure test/folder is present in the directories a,b and c.