bad captain
bad captain

Reputation: 1

How to loop over folders of a directory?

Suppose I am in the directory a1 and there is another directory submissions in a1. without using cd to submissions, how can I print of the folder names in submissions while staying in a1? Can I do the following? I am shell-scripting.

for dir in */submissions; do ... done

Upvotes: 0

Views: 46

Answers (3)

Darkman
Darkman

Reputation: 2991

You can also achieve that using recursions.

#!/bin/sh

func () { # $1=directory
    for file in "$1"/*; do
        if [ -d "$file" ]; then
            func "$file" # Enter another recursion if "$file" is a folder.
        else
            echo "$file" # Print filename
        fi
    done
}

cd a1
func '.'
# Or this for absolute paths
# func "$(realpath .)"

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149155

Using a bourne or Posix shell, you can do:

for dir in ./submission/*
do
    if test -d $dir
    then ...
    fi
done

Upvotes: 1

Fudgy
Fudgy

Reputation: 165

Suppose that this is the folder structure you have:

/a1/submissions/file1
/a1/submissions/file2
/a1/submissions/file3

You can use the ls [OPTIONS] [FILES] command to get a list of files and or directories:

If you provide ls with an absolute path (meaning starting from the "root" level) you can list the contents of that path regardless of where you currently are (provided you have the access rights).

So to get a list of all files in the submissions subfolder, you can run ls /a1/submissions which will output something like this:

file1
file2
file3

Upvotes: 0

Related Questions