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.

Darren rogers
  • 627
  • 2
  • 8
  • 17
  • Ignacio has provided a good solution here [how-to-get-the-list-of-files-in-a-directory-in-a-shell-script](https://stackoverflow.com/questions/2437452/how-to-get-the-list-of-files-in-a-directory-in-a-shell-script) – nagendra547 Aug 16 '17 at 07: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. – user1934428 Aug 16 '17 at 07:04

2 Answers2

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).

heemayl
  • 39,294
  • 7
  • 70
  • 76
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

SLePort
  • 15,211
  • 3
  • 34
  • 44
  • 1
    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.. – Anubis Aug 16 '17 at 07:33
  • 1
    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 – Anubis Aug 16 '17 at 07:37