How can I list the current directory or any directory path contents without using ls command? Can we do it using echo command?
-
found it! " echo * " will do the job. – kashminder Aug 11 '15 at 11:33
2 Answers
printf '%s\n' *
as a shell command will list the non-hidden files in the current directory, one per line. If there's no non-hidden file, it will display * alone except in those shells where that issue has been fixed (csh, tcsh, fish, zsh, bash -O failglob).
echo *
Will list the non-hidden files separated by space characters except (depending on the shell/echo implementation) when the first file name starts with - or file names contain backslash characters.
It's important to note that it's the shell expanding that * into the list of files before passing it to the command. You can use any command here like, head -- * to display the first few lines (with those head implementations that accept several files), stat -- *...
I you want to include hidden files:
printf '%s\n' .* *
(depending on the shell, that will also include . and ..). With zsh:
printf '%s\n' *(D)
Among the other applications (beside shell globs and ls) that can list the content of a directory, there's also find:
find . ! -name . -prune
(includes hidden files except . and ..).
On Linux, lsattr (lists the Linux extended file attributes):
lsattr
lsattr -a # to include hidden files like with ls
- 544,893
If you just want a list of directory contents:
find . -maxdepth 1
or for any other dir:
find <dir> -maxdepth 1
- 1,505
-
1Note that it includes hidden files except
...-maxdepthis a GNU extension (now supported by a few other implementations); the portable/standard equivalent would be:find . -name . -o -pruneorfind . ! -name . -pruneif you don't care for the.entry). – Stéphane Chazelas Aug 11 '15 at 12:41