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?

  • 1
    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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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