linux - bash:运行 "find --exec ..."命令并终止 "\;",全部存储在变量中?

标签 linux bash find escaping exec

我试图在 bash 脚本中找到一种方法来构建一个 find 命令,并将 -exec 存储在变量中,但我无法获取如果它是变量的一部分,则终止 \; 以便被正确识别。

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

local all_the_things=($($cmd \;))

我不确定当 $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

我想将每个文件名 1A1B 发送到 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中吗?或者我可以放心,在 ($( ... )) 内添加 \; 以后不会破坏其他内容吗?

最佳答案

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

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

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

另一种可能性是使用 BASH 函数:

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

关于linux - bash:运行 "find --exec ..."命令并终止 "\;",全部存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31437629/

相关文章:

linux - Bash 脚本 - 使用 find -exec cp 的 For 循环产生错误 : cp: omitting directory

linux - Docker 日期的 ISO 时间戳

linux - 连接变量的问题,cat 和 cut 命令的结果

linux - 从查找 linux 中排除一个目录

python - 在嵌套的有序字典 python 中查找给定键的值

java - java中的mongodb嵌套搜索查询

linux - bash 命令 history -r 做什么?

linux - 无法清除父级为 init 的僵尸进程

c - 在 C 预处理器中避免双重宏替换

bash - 在 bash 中的文件中维护一定数量的带有参数的并发作业