How to display file details (size, date, etc.) from Linux “locate” command?

The (slow) Linux “find” command has an option, “-ls”, to display size, date, etc. like the “ls -l” command. But the “locate” command doesn’t seem to have that. So how can I get the equivalent functionality with locate?

I’ve used back-ticks to pass the output of locate to ls, like this:

ls -al `locate -e somefile`

…which works as long as somefile exists. But if somefile doesn’t exist, it gives me a full directory listing.

If I do this:

ls -al `locate -e somefile` thisfileneverexists

…then it sort of works, if you don’t mind the error line:

ls: cannot access thisfileneverexists: No such file or directory

…which leads us to the obvious-but-extremely-ugly workaround:

ls -al `locate -e somefile` thisfileneverexists 2>/dev/nul

That works, but surely there’s a better way!


Solution 1:

Use xargs. This takes as input a series of parameters, and carries out an operation on them:

 locate -eb0P somefile | xargs -r0 ls -ald

xargs will carry out the ls -ald command using the results of the locate as parameters.

The -e switch tells locate to check that files found in the database really exist, and ignore any which don't.

The -b switch tells locate to match just basenames.

The -0 (zero) switch tells locate to generate null delimiters instead of blanks (so it can handle file names which contain blanks)

The -P switch tells locate to list broken symlinks

The -r switch tells xargs to not carry out the command if nothing is passed in - ie when the locate returns nothing.

The -0 switch tells xargs to expect nulls instead of blanks as delimiters

The -a switch tells ls to list even files that begin with "."

The -d switch tells ls to list directories rather than their contents

Solution 2:

Store the result of locate in a variable, check to see if it has any value, and then view that.

f=`locate ...`
[ "$f" ] && ls -al "$f"

The reason you can't get this information from locate directly is because it's not in the database that locate uses.