Loop through all folders and executing script

I have a bash script install.sh in my current directory and I have a directory apps which contains multiple directories. I want to loop through these sub directories in app folder and execute some script. After executing script in first folder it should come back and enter into next folder. I have tried this but it's skipping one after another. I mean it's entering into all odd folders and not entering into even folders.

Code in install.sh

for f in apps/*; do [ -d $f ] && cd "$f" && echo Entering into $f and installing packages cd .. done; 
1

2 Answers

Use full path of your parent directory(in my case apps directory located in my home directory) and remove one extra command(cd ..)

for dir in ~/apps/*; do [ -d "$dir" ] && cd "$dir" && echo "Entering into $dir and installing packages" done;

See screenshot: with cd .. command and using apps/*

enter image description here

See screenshot: without cd .. command and using ~/apps/*

enter image description here

6

You can use find along with exec for this propose. Your install.sh should be

#!/bin/bash
find ./apps -type d -exec echo Entering into {} and installing packages \; 

replace text after -exec with your command

for example

#!/bin/bash
find ./apps -type d -exec touch {}/test.txt \; 

It will loop through app and all its sub-directories and will create a text.txt file

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like