What's the difference between these ls command line arguments: -d vs *

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 └── file2
  • ls dir lists the contents of dir (one line for file1, one for subdir)
  • ls -d dir only lists dir (on a single line)
  • ls dir/* is expanded to ls dir/file1 dir/subdir and so expands subdir to list its contents
  • ls -d dir/* is expanded to ls dir/file1 dir/subdir, but due to the -d subdir is not expanded and only file1 and subdir are listed (so you get the same output as in the first case).

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like