Ubuntu – listing files in a directory without listing subdirectories and their contents in that directory

ls

I want to create a list of all the files in a directory, without listing any of the subdirectories that reside in that same directory, and print that list to a new file.

ls -d * > filelist

will create a list of all the files in the current directory, but it also lists the subdirectories in the current directory.
I tried the find command using the -maxdepth 1 option – however, the output format is a problem as find also prints out the path along with the file names.

If anyone can please tell me perhaps another command or options to use that will produce an output list of just the files in a directory and not the names of the subdirectories or their contents, I would appreciate it.

Best Answer

Find-based solution:

find . -maxdepth 1 -type f -printf '%f\n'

Bash-based solution:

for f in *; do [[ -d "$f" ]] || echo "$f"; done
##  or, if you want coloured output:
for f in *; do [[ -d "$f" ]] || ls -- "$f"; done

The bash-based solution will get you everything that isn't a directory; it will include things like named pipes (you probably want this). If you specifically want just files, either use the find command or one of these:

for f in *; do [[ -f "$f" ]] && echo "$f"; done
##  or, if you want coloured output:
for f in *; do [[ -f "$f" ]] && ls -- "$f"; done

If you're going to be using this regularly, you can of course put this into an alias somewhere in your ~/.bashrc:

alias lsfiles='for f in *; do [[ -f "$f" ]] && ls -- "$f"; done'

Since you noted in the comments that you're actually on OSX rather than Ubuntu, I would suggest that next time you direct questions to the Apple or more general Unix & Linux Stack Exchange sites.