linux - 从 shell 脚本中的变量运行命令

标签 linux bash shell find

我编写了这段代码来扫描目录以查找比引用文件更新的文件,同时排除特定的子目录。

#!/bin/bash

dateMarker="date.marker"
fileDate=$(date +%Y%m%d)
excludedDirs=('./foo/bar' './foo/baz' './bar/baz')
excludedDirsNum=${#excludedDirs[@]}

for (( i=0; i < $excludedDirsNum; i++)); do
    myExcludes=${myExcludes}" ! -wholename '"${excludedDirs[${i}]}"*'"
done

find ./*/ -type f -newer $dateMarker $myExcludes > ${fileDate}.changed.files

然而,排除项只是被忽略了。当我“echo $myExcludes”时,它看起来很好,此外,如果我用 echo 命令的输出替换最后一行中的“$myExcludes”,脚本的行为就像预期的那样。我猜这是某种引用/转义错误,但我无法消除它。

最佳答案

似乎是引用问题,尝试使用数组:

#!/bin/bash

dateMarker=date.marker
fileDate=$(date +%Y%m%d)
excludedDirs=('./foo/bar' './foo/baz' './bar/baz')
args=(find ./*/ -type f -newer "$dateMarker")
for dir in "${excludedDirs[@]}"
do
    args+=('!' -wholename "$dir")
done
"${args[@]}" > "$fileDate.changed.files"

也许你还需要-prune:

args=(find ./*/)
for dir in "${excludedDirs[@]}"
do
    args+=('(' -wholename "$dir" -prune ')' -o)
done
args+=('(' -type f -newer "$dateMarker" -print ')')

关于linux - 从 shell 脚本中的变量运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3150717/

相关文章:

linux - 调整大小不遵守分辨率规范

linux - 在另一个目录中运行 bash 脚本

bash - grep、tee 和 sleep 一起玩得不好

android - 从 Android Studio 运行 Gradle 脚本时未加载 Bashrc

macos - Mac Bash - 无法识别 if[$#=0]

linux - 使用 sed 删除 _ 和 - 字符

ruby - 如何解决 brewlinux 缺少的@rb_readlink?

linux - 为什么在编写 linux 服务时出现 Exec 格式错误?

linux - linux中fat32的最大容量是多少?

linux - 用于读取日志的 IP 表脚本