3

I am writing a shell script.. given a a folder as a command line arg it will print out the names of the files/folders in it

#!/bin/sh
folder="$1"
for f in "$folder"
do
  echo "$f"
done

This only prints out some the first file/folder of the given folder.

2
  • Ignacio has provided a good solution here how-to-get-the-list-of-files-in-a-directory-in-a-shell-script Commented Aug 16, 2017 at 7:04
  • 2
    @Darrenrogers: Actually it doesn't. Your program just output the first parameter which is passed to your script, whatever it is. Note also that you have - perhaps incorrectly - tagged your question with bash. Unless you explicitly invoke this script by bash SCRIPTNAME ..., it won't be executed by bash, but by sh. I suggest that you remove the bash tag. Commented Aug 16, 2017 at 7:04

2 Answers 2

5

You need shell globbing operator * after $folder separated by the directory separator /:

for f in "$folder"/*
do
  echo "$f"
done

* would expand to all files inside $folder.

As an aside, i see you have used sh (not bash) as the script interpreter; sh is not bash in all systems (e.g. in Ubuntu), so if you were to use bash (does not make any difference in this case though), explicitly use bash in the Shebang (e.g. #!/usr/bin/env bash).

Sign up to request clarification or add additional context in comments.

1 Comment

as nullglob option is off by default, a check [[ -e $f ]] may be added in case glob expands to $folder'/*'
1

You can also use a find command:

folder="$1"
find "$folder"

As @Anubis pointed out in comments, the find command is recursive by default: it will also search for files/folders into subdirectories starting from target folder. You can restrict results to the current directory with the -mindepth and -mindepth options:

find "$folder" -mindepth 1 -maxdepth 1

Note that the target directory will be listed too if you omit -mindepth 1

2 Comments

yes but this will start from the target directory and recurse into all the subdirectories. Better to mention that this can be controlled with mindepth and maxdepth. e.g. find "$folder" -mindepth 1 -maxdepth 1 will list only the first level content etc..
It must be noted that here, if -mindepth 1 is omitted, target directory also will be listed, which is not produced in the answer given by heemayl

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.