I\'m trying to get the contents of a directory using shell script.
My script is:
for entry in `ls $search_dir`; do
echo $entry
done
The other answers on here are great and answer your question, but this is the top google result for "bash get list of files in directory", (which I was looking for to save a list of files) so I thought I would post an answer to that problem:
ls $search_path > filename.txt
If you want only a certain type (e.g. any .txt files):
ls $search_path | grep *.txt > filename.txt
Note that $search_path is optional; ls > filename.txt will do the current directory.
Here's another way of listing files inside a directory (using a different tool, not as efficient as some of the other answers).
cd "search_dir"
for [ z in `echo *` ]; do
echo "$z"
done
echo *
Outputs all files of the current directory. The for
loop iterates over each file name and prints to stdout.
Additionally, If looking for directories inside the directory then place this inside the for
loop:
if [ test -d $z ]; then
echo "$z is a directory"
fi
test -d
checks if the file is a directory.
On the Linux version I work with (x86_64 GNU/Linux) following works:
for entry in "$search_dir"/*
do
echo "$entry"
done
for entry in "$search_dir"/*
do
echo "$entry"
done
The accepted answer will not return files prefix with a . To do that use
for entry in "$search_dir"/* "$search_dir"/.[!.]* "$search_dir"/..?*
do
echo "$entry"
done
Just enter this simple command:
ls -d */