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/dir1The form of it would be either
ls -<something> .or
ls -<something> /a/b/cI 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?
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/cwhich is equivalent to
find /a/b/c -printThere are two problems here:
/a/b/cwill also be printed.findworks recursively. It's not clear ifdir1in 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 1These 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 -pruneSole /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.