What's the difference between
ls /example or ls /example/vs
ls -d /example/*Why do they give (almost) the same output?
2 Answers
In the first case, you're giving ls a directory and asking to show its contents.
In the second case, you're already giving ls the contents directly (a list of individual files & subdirectories), and asking to show exactly those items but not their further contents.
So these give the same output because they do nearly the same thing, except in the former case ls itself determines what contents it needs to show, while in the latter case you're giving it a pre-determined list.
Ls has two modes: when given a file, it shows just that file; when given a directory, it shows the contents of that directory (one level deep).
Your /example is a directory, so when you use ls /example, ls will show its contents. The -d option disables this behavior and makes ls always show just the item given, whether it's a file or not.
(Compare: ls -l /etc and ls -l -d /etc)
But when you use ls -d /example/*, you're not asking it to show a directory – you're giving it a list of individual items to show. The wildcards are expanded by your shell before the command gets run, so what you're really running is ls -d /example/file1 /example/file2 /example/file3.
When an argument to ls is a directory, ls enters the directory and lists the directory contents, unless it was called with -d. And remember that the filename expansion ('file*') is done in the shell before calling ls, so it you have:
dir
├── file1
└── subdir └── file2ls dirlists the contents ofdir(one line forfile1, one forsubdir)ls -d dironly listsdir(on a single line)ls dir/*is expanded tols dir/file1 dir/subdirand so expandssubdirto list its contentsls -d dir/*is expanded tols dir/file1 dir/subdir, but due to the-dsubdiris not expanded and onlyfile1andsubdirare listed (so you get the same output as in the first case).