Home > Software engineering >  Shell script to list all files in a directory
Shell script to list all files in a directory

Time:03-03

I am using the following code :

#!/bin/bash
for f in $1 ; do
        echo $f
done 

The aim is to list down all the files in the directory that is passed as an argument to this script. But it's not printing anything. Not sure what could be wrong with this.

CodePudding user response:

If you only need to list files not directories. (this part is unclear to me.) find is your friend.

find $1 -depth 1 -type file

Returns:

./output.tf
./locals.tf
./main.tf
./.tflint.hcl
./versions.tf
./.pre-commit-config.yaml
./makefile
./.terraformignore
./jenkins.tf
./devops.tf
./README.md
./.gitignore
./variables.tf
./Jenkinsfile
./accounts.tf
./.terraform.lock.hcl

Furthermore, please run man find.

CodePudding user response:

Try this Shellcheck-clean pure Bash code for the "further plan" mentioned in a comment:

#! /bin/bash -p

# List all subdirectories of the directory given in the first positional
# parameter.  Include subdirectories whose names begin with dot.  Exclude
# symlinks to directories.

shopt -s dotglob
shopt -s nullglob
for d in "$1"/*/; do
    dir=${d%/}                  # Remove trailing slash
    [[ -L $dir ]] && continue   # Skip symlinks
    printf '%s\n' "$dir"
done
  • shopt -s dotglob causes shell glob patterns to match names that begin with a dot (.). (find does this by default.)
  • shopt -s nullglob causes shell glob patterns to expand to nothing when nothing matches, so looping over glob patterns is safe.
  • The trailing slash on the glob pattern ("$1"/*/) causes only directories (including symlinks to directories) to be matched. It's removed (dir=${d%/}) partly for cleanliness but mostly to enable the test for a symlink ([[ -L $dir ]]) to work.
  • See the accepted, and excellent, answer to Why is printf better than echo? for an explanation of why I used printf instead of echo to print the subdirectory paths.
  • Related