How to get the list of files in a directory in a shell script?
search_dir=/the/path/to/base/dir/
for entry in "$search_dir"/*
do
echo "$entry"
done
This is a way to do it where the syntax is simpler for me to understand:
yourfilenames=`ls ./*.txt`
for eachfile in $yourfilenames
do
echo $eachfile
done
./
is the current working directory but could be replaced with any path*.txt
returns anything.txt
You can check what will be listed easily by typing the ls
command straight into the terminal.
Basically, you create a variable yourfilenames
containing everything the list command returns as a separate element, and then you loop through it. The loop creates a temporary variable eachfile
that contains a single element of the variable it's looping through, in this case a filename. This isn't necessarily better than the other answers, but I find it intuitive because I'm already familiar with the ls
command and the for loop syntax.