bash:run" find --exec ..."终止" \;"的命令,都存储在变量中?

时间:2015-07-15 17:53:24

标签: linux bash find escaping exec

我试图在bash脚本中找到一种方法来构建一个find命令,其中-exec存储在一个变量中,我无法获得终止{{如果它是变量的一部分,则可以正确识别。

当我通过变量调用命令时,我可以通过添加\;来解决它:

\;

我不确定local all_the_things=($($cmd \;)) 存储不同命令时可能会如何相互作用(有几种截然不同的上下文有不同的方法来获取我需要的列表,其中只有一种是通过{ {1}}命令)。

例如,如果我有以下目录和文件,

$cmd

我想将每个文件名find$ ls -l /tmp/dir1 total 0 -rw-r--r-- 1 joeuser joemama 0 Jul 15 10:19 1A -rw-r--r-- 1 joeuser joemama 0 Jul 15 10:19 1B 发送到1A。以下是我尝试过的几种方式:

1B

输出:

basename

有没有办法正确逃脱" \;"所以它可以存储在#!/bin/bash cmd="find /tmp/dir1 -exec basename {} \;" echo; echo "One slash: $cmd" $cmd cmd="find /tmp/dir1 -exec basename {} \\;" echo; echo "Two slashes: $cmd" $cmd cmd="find /tmp/dir1 -exec basename {} \\\;" echo; echo "Three slashes: $cmd" $cmd # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # The first of these gets the desired result, but I want the "\;" in $cmd. # The second shows that the "\;" is being treated as part of the -exec # option, not its terminator. cmd="find /tmp/dir1 -exec basename {}" echo; echo "No slash, will add extra '\;': $cmd" $cmd \; cmd="find /tmp/dir1 -exec echo {} \;" echo; echo "Command is echo, not basename. One slash, will add extra '\;': $cmd" $cmd \; ?或者我可以放心,在$ /tmp/gofind1 One slash: find /tmp/dir1 -exec echo {} \; find: -exec: no terminating ";" or "+" Two slashes: find /tmp/dir1 -exec echo {} \; find: -exec: no terminating ";" or "+" Three slashes: find /tmp/dir1 -exec echo {} \\; find: -exec: no terminating ";" or "+" No slash, will add extra '\;': find /tmp/dir1 -exec echo {} dir1 1A 1B Command is echo, not basename. One slash, will add extra '\;': find /tmp/dir1 -exec echo {} \; /tmp/dir1 \; /tmp/dir1/1A \; /tmp/dir1/1B \; 内添加$cmd会在以后打破其他内容吗?

2 个答案:

答案 0 :(得分:3)

您可以将它们存储到BASH数组中:

cmd=(find /tmp/dir1 -exec basename {} \;)

# then execute it as:
"${cmd[@]}"

另一种可能性是使用BASH功能:

cmdfn() {
   find /tmp/dir1 -exec basename {} \;
}

答案 1 :(得分:-1)

要么我们使用变量,要么使用数组,我们应该评估' eval'获得正确的输出

cmd="find /tmp/dir1 -exec basename {} \;"
eval "${cmd}"