Monday, 13 August 2012

Linux simple find samples

Find stays one of the most confusing Linux commands around. Here I want to simplify the most common ways of using find.

There is many an article out there, but I think they all go into to much detail. I just want to find some files, and do something with them. Also I cannot believe that people show samples using the rm command. What the?

Do you want n00bs to delete files from there servers?

All mine, I'm using ls, so nothing should go wrong.

Also be careful not to test from your / folder, you will get weird errors and it will fall over when hitting stuff like your /dev/ and /proc/ folders. Start small.

1. Find a file:

find /mnt/some/where -type f -name "FILENAME"
find /mnt/some/where -type f -iname "FILENAME"

The first will match the filename exactly, and the second will match exactly ignoring the case. Both these will return the full path to the matched file(s). Adding an * into the filename will find partial filenames.

find /mnt/some/where -type f -name "FILENAM*"
find /mnt/some/where -type f -iname "*ILENAM*"

2. Do something with the file:

Here you have many options, and all confusing. Look at these two samples:

find /mnt/some/where -type f -iname "*ILENAM*" | xargs ls -al;
find /mnt/some/where -type f -iname "*ILENAM*" -exec /bin/ls -al '{}' \;

Both will yield the same result. Please note the "\;" and the end of the -exec command to show the executed ls command it ends. The xargs will add the output from find to the end of the piped (|) command. The '{}' sets where you want to put the command called in the -exec section.

In both cases the ls will run for each returned result from find.

3. Complex do something:

The result can be passed multiple times using the -exec command in find. The problem however is that sometime the execution runs incorrectly. Have a look at this sample:

find /mnt/some/where -type f -iname "*ILENAM*" -exec /bin/ls -al $(basename '{}') \;

This is summuse to return a file not found error as we are only running the ls for the filename part of the returned find. You however still get a ls on the full name.

find /mnt/some/where -type f -iname "*ILENAM*" -exec bash -c '/bin/ls -al $(basename "{}")' \;

This one works correctly. Please note the use of ' to set the bash command string.


Mommy, I found it! — 15 Practical Linux Find Command Examples -
A Unix/Linux “find” Command Tutorial -

ProxMox Unprivileged LXC containers USB Drive

Some quick notes on bind mounting under ProxMox and getting the permissions right. Reference -