建立用于查找的命令字符串 [英] Building up a command string for find

查看:61
本文介绍了建立用于查找的命令字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析android源目录,我需要提取所有目录名称(不包括某些模式).如果您在下面注意到.,到目前为止,我仅在排除列表中包含1个目录,但是我将添加更多目录.

I'm trying to parse the android source directory and i need to extract all the directory names excluding certain patterns. If you notice below., for now i included only 1 directory to the exclude list, but i will be adding more.,

find命令不会排除名称为'docs'的目录.

The find command doesn't exclude the directory with name 'docs'.

注释掉的行有效.但是另一行无效.为了方便调试,我提供了min和maxdepth,以后将删除.

The commented out line works., but the other one doesn't. For easy debugging, i included the min and maxdepth which i would remove later.

是否有任何评论或提示为何无效?

Any comments or hints on why it doesn't work?

#! /bin/bash
ANDROID_PATH=$1
root=/
EXCLUDES=( doc )
cd ${root}
for dir in "${EXCLUDES[@]}"; do
    exclude_name_cmd_string=${exclude_name_cmd_string}$(echo \
                            "-not -name \"${dir}*\" -prune")
done
echo -e ${exclude_name_cmd_string}
custom_find_cmd=$(find ${ANDROID_PATH} -mindepth 1 -maxdepth 1 \
                    ${exclude_name_cmd_string} -type d)
#custom_find_cmd=$(find ${ANDROID_PATH} -mindepth 1 -maxdepth 1 \
#                    -not -name "doc*" -prune -type d)
echo ${custom_find_cmd} 

推荐答案

使用可能带有引号的参数构建命令字符串是一个坏主意.您会陷入嵌套的引用级别和 eval 以及许多其他危险/令人困惑的语法问题中.

Building up a command string with possibly-quoted arguments is a bad idea. You get into nested quoting levels and eval and a bunch of other dangerous/confusing syntactic stuff.

使用数组构建 find ;您已经将EXCLUDES合二为一.

Use an array to build the find; you've already got the EXCLUDES in one.

此外,重复的 -not -prune 在我看来很奇怪.我会这样写你的命令:

Also, the repeated -not and -prune seems weird to me. I would write your command as something like this:

excludes=()

for dir in "${EXCLUDES[@]}"; do
  excludes+=(-name "${dir}*" -prune -o) 
done

find "${ANDROID_PATH}" -mindepth 1 -maxdepth 1 "${excludes[@]}" -type d -print

结果是,您希望将-名称的参数作为 find 将扩展的文字通配符传递给 find Shell扩展返回的文件列表,或包含文字引号的字符串.如果您尝试将命令构建为字符串,则很难做到这一点,但如果使用数组,则很难做到这一点.

The upshot is, you want the argument to -name to be passed to find as a literal wildcard that find will expand, not a list of files returned by the shell's expansion, nor a string containing literal quotation marks. This is very hard to do if you try to build the command as a string, but trivial if you use an array.

朋友不要让朋友将外壳命令构建为字符串.

Friends don't let friends build shell commands as strings.

这篇关于建立用于查找的命令字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆