10

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!

3 Answers 3

15

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

2
  • 1
    Unfortunately, that breaks for files with blanks in the names, and also for directory names that match the pattern. This works better: "locate -eb0 somefile | xargs -r --null ls -ald" The options mean: locate -e = only match files that actually exist -b = match basename -0 = use null delimiters instead of spaces xargs --null = expect null delimiters instead of spaces ls -d = list directories rather than their contents -a = list even hidden files (with names which begin with ".") May 29, 2013 at 15:12
  • +1: This is gold. It is the way I want locate to work, since finding a file isn’t always enough — finding the date and size of a file will help to distinguish it from others.
    – Manngo
    May 21, 2018 at 9:34
3

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.

0

You can also loop through the locate output:

locate somefile | while IFS= read -r i; do ls -la "$i"; done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .