Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to write a simple shell script that will go into all the sub-folders in a directory, and organise the files in the sub-folders into new directories. Basically in terminal it would look like:

cd ../subfolder1
mkdir newfolder
mv *.txt newfolder
cd ../subfolder2
mkdir newfolder
mv *.txt newfolder

However, the cd command doesn't seem to work for the shell script. Anyone know how I could do this? Thanks a million!

share|improve this question
Please explain - why do you say that cd doesn't work for shell scripts? Of course it does... – Rmano Apr 22 '14 at 0:59
@bobleponge314 cd works in shell scripts, it just doesn't change the directory outside of the shell script. – Eliah Kagan Sep 21 '14 at 12:53

If your directory structure is as follow:

├── subfolder1
│   ├── foo.txt
│   └── bar.other
└── subfolder2
    ├── foo2.txt
    └── baz.old

Running the following command:

find . -maxdepth 1 ! -path . -type d -exec sh -c "mkdir {}/newfolder && mv {}/*.txt {}/newfolder" \;

Will create the below tree structure:

├── subfolder1
│   ├── newfolder
│   │   └── foo.txt
│   ├── bar.other
└── subfolder2
    ├── newfolder
    │   └── foo2.txt
    ├── baz.old
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.