Why use the Linux find command with caution?

Recently, a friend reminded me that there is a useful option to run the find command more cautiously, which is -ok. Except for one important difference, it works similarly to -exec in that it causes the find command to request permission before performing the specified operation.

Here is an example. If you use the find command to find files and delete them, you might use the following command:

$ find . -name runme -exec rm {} ;

Any files named "runme" in the current directory and its subdirectories will be deleted immediately-of course, you must have permission to delete them. Use the -ok option instead, and you will see something like this, but the find command will ask for permission before deleting the file. Answering y for "yes" will allow the find command to continue and delete files one by one.

$ find . -name runme -ok rm {} ;

< rm … ./bin/runme > ?

-execdir command is also an option

Another option that can be used to modify the behavior of the find command, and possibly make it more controllable, is -execdir. -exec will run any command specified, and -execdir will run the specified command from the directory where the file is located, instead of running the specified command in the directory where the find` command is run. Here are two examples of it:

$ pwd

/home/shs

$ find . -name runme -execdir pwd ;

/home/shs/bin

$ find . -name runme -execdir ls ;

ls rm runme

So far so good. But remember that -execdir will also execute the command in the directory of the matching file. If you run the following command and the directory contains a file named "ls", it will run the file even if the file does not have execute permission. Using -exec or -execdir is similar to running commands through source.

$ find . -name runme -execdir ls ;

Running the /home/shs/bin/ls file

$ find . -name runme -execdir rm {} ;

This is an imposter rm command

$ ls -l bin

total 12

-r-x------ 1 shs shs 25 Oct 13 18:12 ls

-rwxr-x— 1 shs shs 36 Oct 13 18:29 rm

-rw-rw-r-- 1 shs shs 28 Oct 13 18:55 runme

$ cat bin/ls

echo Running the $0 file

$ cat bin/rm

echo This is an imposter rm command

-okdir option will also request permission

To be more cautious, you can use the -okdir option. Similar to -ok, this option will request permission to run the command.

$ find . -name runme -okdir rm {} ;

< rm … ./bin/runme > ?

You can also be careful to specify the full path of the command you want to use to avoid any problems with fake commands like the one above.

$ find . -name runme -execdir /bin/rm {} \

The find command has many options besides the default printing. Some can make your file search more precise, but it is always good to be careful.

Guess you like

Origin blog.csdn.net/newdreamIT/article/details/101541592