Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script print out file names when given a folder [duplicate]

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.

like image 926
Darren rogers Avatar asked Jan 18 '26 10:01

Darren rogers


2 Answers

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

like image 97
heemayl Avatar answered Jan 21 '26 05:01

heemayl


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

like image 32
SLePort Avatar answered Jan 21 '26 03:01

SLePort