captain
captain

Reputation: 1827

How do I traverse through every file in a folder?

I have a folder called exam. This folder has 3 folders called math, physics and english. All of these folders have some sub folders and files in them. I want to traverse through every folder and print the path of every folder and file on another file called files. I've done this:

#!/bin/bash

LOC="/home/school/exam/*"

{
  for f in $LOC 
  do
   echo $f
  done
 } > "files"

The exit I get is:

/home/school/exam/math

/home/school/exam/physics

/home/school/exam/english

I can't figure out how to make the code visit and do the same thing to the sub folders of exam. Any suggestions?

PS I'm just a beginner in shell scripting.

Upvotes: 1

Views: 811

Answers (5)

ZenGyro
ZenGyro

Reputation: 176

You can also use the tree command which is included in most *nix distributions. (Though Ubuntu is a notable exception - but can be installed via apt-get)

LOC="/home/school/exam/"
tree -if $LOC > files

Upvotes: 0

Benoit
Benoit

Reputation: 79165

With the globstar option bash will recurse all filenames in subdirectories when using two adjacent stars

use :

shopt -s globstar
for i in /home/school/exam/**

The reference here is man bash:

globstar
                      If set, the pattern ** used in a pathname expansion context
                      will match all files and zero or more directories and
                      subdirectories.  If the pattern is followed by a /, only
                      directories and subdirectories match.

and info bash:

          *      Matches any string, including the null string.  When  the
                 globstar  shell  option  is  enabled,  and * is used in a
                 pathname expansion context, two adjacent  *s  used  as  a
                 single  pattern  will  match  all  files and zero or more
                 directories and subdirectories.  If followed by a /,  two
                 adjacent  *s  will match only directories and subdirecto‐
                 ries.

Upvotes: 2

RHT
RHT

Reputation: 5054

How about this to list all your files recursively.

for i in *; do ls -l $i ; done

Upvotes: -1

Kent
Kent

Reputation: 195039

you can use find command, it could get all files, then you can do something on them, using exec or xargs for example.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246764

find /home/school/exam -print > files

Upvotes: 3

Related Questions