从脚本调用时,Bash查找无法返回所有匹配的文件

时间:2017-12-03 23:25:25

标签: linux bash hierarchy

从命令行和bash脚本运行相同的命令会在Ubuntu 16.04上产生不同的结果。

我有一个包含以下内容的文件夹:

├── audio
│   └── delete_me.mp3
├── words
│   └── audio
│       └── delete_me.mp3
│   └── images
│       └── delete_me.jpg
└── keep_me.txt

我有一个名为findKeepers.sh的bash脚本:

#!/usr/bin/env bash

findKeepers () {
  local dir=$1
  echo "$(find $dir -type f ! -name delete_me*)"
}

findKeepers /path/to/directory

我希望它输出keep_me.txt文件的路径。相反,我得到一个空白行。

 

如果我从命令行运行看起来相同的命令,我得到了我期望的结果:

dir=/path/to/directory; echo "$(find $dir -type f ! -name delete_me*)"
/path/to/directory/keep_me.txt

如果搜索所有未调用keep_me的文件,则bash脚本会忽略音频文件夹。这是另一个名为findUnwanted.sh的bash脚本:

#!/usr/bin/env bash

findUnwanted () {
  local dir=$1 
  echo "$(find $dir -type f ! -name keep_me*)"
}

findUnwanted /path/to/directory

结果如下:

$ ./findUnwanted.sh
/path/to/directory/words/audio/delete_me.mp3    
/path/to/directory/words/images/delete_me.jpg

如果我从命令行运行同样的东西,我会得到所有三个delete_me文件:

$ dir=/path/to/directory; echo "$(find $dir -type f ! -name keep_me*)"
/path/to/directory/words/audio/delete_me.mp3    
/path/to/directory/words/images/delete_me.jpg
/path/to/directory/audio/delete_me.mp3    

在我看来,bash脚本首先深入到words文件夹,然后再不出来搜索相邻的文件夹或文件。 #!/usr/bin/env bash环境有什么特别之处吗?还是我还没有看到其他一些差异?

CODA:我猜测它是导航错误,因为经过多次修改后它又开始为我工作了。对于任何感兴趣的人,我的函数的最终版本如下所示。

#!/usr/bin/env bash

# Returns 1 if the given directory contains only placeholder files, or
# 0 if the directory contains something worth keeping
checkForDeletion () {
  local _dir=$1
  local _temp=$(find "$_dir" -type f ! -regex '.*\(unused.txt\|delete_me.*\)')

  if [ -z "$_temp" ]
  then
   return 1
  fi
}

我这样用:

parent=/path/to/parent/
for dir in $parent*/
do
  checkForDeletion $dir
  if [ $? = 1 ]
  then
    echo "DELETE? $dir" # rm -rf $dir
  fi
done

1 个答案:

答案 0 :(得分:0)

我猜你的'!'打破整个管道。请尝试使用'-not',因此您的第一个代码段应如下所示:

  echo "$(find $dir -type f -not -name delete_me*)"

我不善于解释你应该逃避特殊字符的位置以及不在哪里,但是当使用外部函数时事情的工作方式不同表明逃避可能是问题。