Miro Feliciano
Miro Feliciano

Reputation: 79

How can I check the existence of several subfolders

I have several folders with 4 letters, all of them have the same subfolders (joint), and in each of these subfolders there might be the folder 01, 02 and all. What I want to do is enter all 4-letter-folders and subsequent joint folder and see if there is a 02 folder in it or not. If there is it should give me the contents of the all folder, if it does not, it should show me the contents of the 01 folder

Here is what I have so far

#!/bin/bash
  
dir=$(pwd)

for folder in ????

do

cd "$folder" || exit

cd joint

if [ -d "/$dir/$folder/joint/02" ]; then
       cd all || exit
fi

if [ ! -d "/$dir/$folder/joint/02" ]; then
       cd 01 || exit
fi

ls

cd ../../..

done

so it would look something like this

1234
 joint
    ├── 01
    ├── 02
    └── all

What I am getting is that the code is running only through one of the folders.

Upvotes: 0

Views: 27

Answers (1)

max.haredoom
max.haredoom

Reputation: 878

Try this...

You will probably have to adopt the inner most if-then-else to fit your needs.

#!/bin/bash

# for all files in the curent dir
for d in `ls -1`; do
    
    # if it is a directory
    if [ -d $d ]; then
    
        # if there is a sub directory "joint"
        if [ -d $d/joint ]; then
        
            # if there is a further sub dir "joint/02"
            if [ -d $d/joint/02 ]; then
                
                # then list the files in $d/joint/all/
                echo "files in $d/joint/all/"
                ls -l $d/joint/all/
            else
                # otherwise list the files in $d/joint/01/
                echo "files in $d/joint/01/"
                ls -l $d/joint/01/
            fi
        fi
    fi 
done

Upvotes: 1

Related Questions