Title: Shell script to function on subfolders
Tags: command-line;bash;scripts;cd-command
Question: 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?
Comment: Please explain - why do you say that `cd` doesn't work for shell scripts? Of course it does...

Comment: @bobleponge314 `cd` works in shell scripts, it just doesn't change the directory *outside* of the shell script.


Here is another answer: 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 &amp;&amp; mv {}/*.txt {}/newfolder" \;
Will create the below tree structure:
├── subfolder1
│   ├── newfolder
│   │   └── foo.txt
│   ├── bar.other
└── subfolder2
├── newfolder
│   └── foo2.txt
├── baz.old

{'source': 'StackExchangeDataset', 'subset': 'askubuntu.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2014:00:04/22/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<command-line><bash><scripts><cd-command>', 'Title': 'Shell script to function on subfolders', 'ViewCount': 157, 'id': 452490, 'user_AboutMe': '', 'user_AccountId': 4360491.0, 'user_DisplayName': 'bobleponge314', 'user_Reputation': 111.0, 'user_Views': 7.0, 'user_id': 272116.0}}