无法shell出来查找命令

问题描述 投票:0回答:1

在Ruby中,我想要发布以下find命令:

find . -type f -name '*.c' -exec mv {} . \;

我尝试过这个命令的许多排列:

  • system("find . -type f -name '*.c' -exec mv {} . \;")
  • `find . -type f -name '*.c' -exec mv {} . \;`
  • %x(find . -type f -name '*.c' -exec mv {} . \;)

但是当我运行命令时,find会生成错误消息:

find: -exec: no terminating ";" or "+"

我不认为问题是需要转义的字符。这可能是一个非常简单的修复,但任何帮助将不胜感激!

ruby
1个回答
0
投票

你需要 - 正如@mudasobwa指出的那样 - 实际上将反斜杠传递给find命令。如果你在irb中尝试你的字符串,你会立即看到出了什么问题:

>> "find . -type f -name '*.c' -exec mv {} . \;"
=> "find . -type f -name '*.c' -exec mv {} . ;"

但是,对于实际运行find命令,您需要下定决心,无论system还是%x()都是正确的工具。如果你想要处理命令的stdout,你必须使用%x,在这种情况下,你必须转义反斜杠,因为字符串然后被消耗,好像它是双引号之间的字符串:

find_stdout = %x(find . -type f -name '*.c' -exec mv {} . \\;)

如果你对结果不感兴趣,但只对命令的整体成功(退出代码,....)感兴趣,你应该使用system,在这种情况下,你可以使用一个带引号的字符串,这允许你不要逃避反斜杠:

result = system('find . -type f -name "*.c" -exec mv {} . \;')

当然,在这里逃避也没有错,有些人建议一致性和可维护性总是逃避反斜杠。

© www.soinside.com 2019 - 2024. All rights reserved.