linux - 如何使用bash中的变量内容传递给脚本中的查找?

标签 linux string bash find quotes

在 bash 脚本中,我尝试使用一个变量的内容作为 find 命令的选项:

#!/bin/bash
FILE_EXTENSIONS=( txt png jpg )

FIRST=1
for FILE_EXTENSION in ${FILE_EXTENSIONS[@]} 
do
#   echo "$FILE_EXTENSION"
    if [[ $FIRST == 1 ]]
    then
        FIND_FILTER="-iname '*.$FILE_EXTENSION'"
        FIRST=0
    else
        FIND_FILTER="${FIND_FILTER} -o -iname '*.$FILE_EXTENSION'"
    fi
done
# Read and write only for user and group, ignore case '-iname'
#find . -type f "$FIND_FILTER" -exec chmod 660 {} \;
echo Find filter: $FIND_FILTER
# This might work with some already provided suggestions:
find . -type f $FIND_FILTER
# But this fails so far
find . -type f $FIND_FILTER -exec chmod 660 {} \;        
#EOF

目的是设置适当的访问权限,无论出于何种原因,相当多的文件(例如图片或办公文档)都被标记为可执行。

所以实际上上面的脚本有几个文件扩展名串联的数组,但脚本显示了问题。

第一种方法是遍历最终数组并每次调用查找。但从运行时的角度来看,每次都一遍又一遍地搜索是愚蠢的。

我也可以简单地在 python 中执行此操作,但有一次我想我想在 bash 中使用 linux 基本方法来解决它。

看起来 FIND_FILTER 变量的内容是正确的(至少用 echo 打印的是正确的)但是......它不起作用。

有什么问题的建议吗?

最佳答案

您一开始(几乎)正确地使用了数组,但随后放弃了它们,转而使用以空格分隔的字符串。继续使用数组。

  1. 始终引用 @ 的扩展-索引数组;否则,没有理由使用 @* .
  2. 作为一般规则,避免使用全大写的变量名称;它们(大部分)保留供 shell 使用。
  3. 附上由 -o 加入的过滤器在转义括号中,以便 find除了 -type 之外,将它们视为要满足的单一条件初级。
  4. 使用-exec ... +这样chmod每次调用可以对多个文件进行操作,而不是分别为每个文件调用一次。

#!/bin/bash
file_extensions=( txt png jpg )

first=1
for ext in "${file_extensions[@]}"
do
#   echo "$ext"
    if [[ $first == 1 ]]
    then
        find_filter=(-iname "*.$ext")
        first=0
    else
        find_filter+=( -o -iname "*.$ext")
    fi
done


# Read and write only for user and group, ignore case '-iname'
find . -type f \( "${find_filter[@]}" \) -exec chmod 660 +

关于linux - 如何使用bash中的变量内容传递给脚本中的查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41260720/

相关文章:

linux - 简单与神秘的用户名

php - 截断 UTF-8 字符串以适应 PHP 中给定的字节数

c++ - 合并排序 std :string 中的字符

python - str.__getslice__ 没有按预期工作,负停止

bash - 删除字段中的所有重复条目

bash - 使用 FS 时如何抑制 awk 输出?

linux - GoDaddy cpanel 安装 : Trying to install Drush for Drupal and possibly can't find php-cli?

python - 在另一台机器上安装相同的python环境

c - 如何在 ubuntu 11.04 中设置 LD_LIBRARY_PATH

linux - 如何从 PHP (Apache) 调用 ejabberdctl