请谨慎使用Linux find命令

系统 Linux
当使用 Linux 下的 find 命令时,请使用 -ok 选项来避免文件被意外删除,这个选项会在移除任何文件之前都会请求你的许可。

[[220477]]

当使用 Linux 下的 find 命令时,请使用 -ok 选项来避免文件被意外删除,这个选项会在移除任何文件之前都会请求你的许可。

最近有朋友提醒我有一个有用的选项来更加谨慎地运行 find 命令,它就是 -ok。除了一个重要的区别之外,它的工作方式与 -exec 相似,它使 find 命令在执行指定的操作之前请求权限。

这有一个例子。如果你使用 find 命令查找文件并删除它们,你可能使用的是下面的命令:

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

在当前目录及其子目录中中任何名为 “runme” 的文件都将被立即删除 —— 当然,你要有权限删除它们。改用 -ok 选项,你会看到类似这样的东西,但 find 命令将在删除文件之前会请求权限。回答 y 代表 “yes” 将允许 find 命令继续并逐个删除文件。

  1. $ find . -name runme -ok rm {} \;
  2. < rm ... ./bin/runme > ? 

-execdir 命令也是一个选择

另一个可以用来修改 find 命令行为,并可能使其更可控的选项是 -execdir-exec 会运行指定的任何命令,而 -execdir 则从文件所在的目录运行指定的命令,而不是在运行find` 命令的目录运行指定的命令。这是两个它的例子:

  1. $ pwd
  2. /home/shs
  3. $ find . -name runme -execdir pwd \;
  4. /home/shs/bin
  1. $ find . -name runme -execdir ls \;
  2. ls rm runme

到现在为止还挺好。但要记住的是,-execdir 也会在匹配文件的目录中执行该命令。如果运行下面的命令,并且目录包含一个名为 “ls” 的文件,那么即使该文件没有执行权限,它也将运行该文件。使用 -exec-execdir 类似于通过 source 来运行命令。

  1. $ find . -name runme -execdir ls \;
  2. Running the /home/shs/bin/ls file
  1. $ find . -name runme -execdir rm {} \;
  2. This is an imposter rm command
  1. $ ls -l bin
  2. total 12
  3. -r-x------ 1 shs shs 25 Oct 13 18:12 ls
  4. -rwxr-x--- 1 shs shs 36 Oct 13 18:29 rm
  5. -rw-rw-r-- 1 shs shs 28 Oct 13 18:55 runme
  1. $ cat bin/ls
  2. echo Running the $0 file
  3. $ cat bin/rm
  4. echo This is an imposter rm command 

-okdir 选项也会请求权限

要更谨慎,可以使用 -okdir 选项。类似 -ok,该选项将请求权限来运行该命令。

  1. $ find . -name runme -okdir rm {} \;
  2. < rm ... ./bin/runme > ?

你也可以小心地指定你想用的命令的完整路径,以避免像上面那样的冒牌命令出现的任何问题。

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

find 命令除了默认打印之外还有很多选项,有些可以使你的文件搜索更精确,但谨慎一点总是好的。

FacebookLinkedIn 上加入 Network World 社区来进行评论。 

责任编辑:庞桂玉 来源: Linux中国
相关推荐

2009-08-03 10:12:37

find命令详解find命令linux

2010-03-09 13:54:05

Linux find命

2018-05-16 10:32:06

Linux命令find

2009-08-04 08:32:06

Linux Find命Linux Find使用方法

2009-08-03 09:20:18

find命令详解find命令linux find命

2012-05-11 10:07:55

Linuxfind

2010-03-18 16:34:33

Linux命令

2013-06-28 09:25:49

Wi-Fi802.11ac无线网络

2009-08-04 08:44:56

linux find命linux find查找文件命令

2021-12-12 09:19:16

find命令Linux

2011-06-16 10:46:47

图标名称

2013-10-08 16:24:34

Linux find命

2017-12-27 09:40:32

Linuxfind命令

2013-10-08 15:51:03

Linux find命

2013-06-05 16:19:32

Linux管理员find命令

2009-08-03 10:06:22

find命令详解find命令Linux

2022-10-08 08:04:47

FindLinuxLocate

2019-09-12 08:21:22

Linuxfind命令查找

2017-03-17 14:35:38

2019-05-20 10:38:42

UDP协议场合
点赞
收藏

51CTO技术栈公众号