Print only full paths of files and directories using `ls`

For a given directory the request is to print the full paths of files and directories

e.g. for

 /a/b/c/ file1 file2 dir1/

The command should show

/a/b/c/file1
/a/b/c/file2
/a/b/c/dir1

The form of it would be either

ls -<something> .

or

ls -<something> /a/b/c

I would think that would be trivial to achieve but did not find it having perused all of the ls switches. Did I miss it - or should something else like find be used?

2

1 Answer

find can give you the desired format almost by default. It's obliged to use pathnames that start with the path you provided, so provide /a/b/c:

find /a/b/c

which is equivalent to

find /a/b/c -print

There are two problems here:

  1. /a/b/c will also be printed.
  2. find works recursively. It's not clear if dir1 in your example is empty or its content is omitted. You may or may not want recursion.

The problem can be solved by -mindepth 1 and -maxdepth 1 respectively, if your find supports them:

find /a/b/c -mindepth 1 -maxdepth 1

These options are not required by POSIX. With POSIX find you can suppress printing /a/b/c with ! -path /a/b/c; and you can "emulate" -maxdepth 1 by following this: Limit POSIX find to specific depth?

This is a POSIX solution:

find /a/b/c ! -path /a/b/c -prune

Sole /a/b/c will not pass the ! -path test. Anything that passes will be pruned, so the tool will not descend deeper.

Providing the starting path as /a/b/c/ (note the trailing slash) requires you to use ! -path /a/b/c/ (also with a trailing slash) because find is obliged to refer to its starting path exactly as it was provided. /a/b/c/ does not match /a/b/c and vice versa. Remember -path treats is argument as a pattern, this is important if your starting path contains literal * or other characters used in Pattern Matching Notation.


You requested specific format, so maybe you want to parse the output. In this case find is your tool and ls definitely is not, because you shouldn't parse the output of ls. If your find is GNU find, check the UNUSUAL FILENAMES section in man 1 find. Consider -print0.

In a comment you were given a link to this question. Many solutions there require supplying a path to some tool (like readlink). If the original path comes from ls, it's already an act of "parsing ls" – not recommended.

However tools from this other question may be useful in your case to turn a relative path like ./c or c to full path like /a/b/c. Then you provide the full path to find.

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