搜索路径底部向上bash中的文件

时间:2015-06-29 19:43:14

标签: bash search

使用bash脚本,我希望尝试根据路径搜索文件,但是我想从路径的底部搜索。比如/ path / to / directory / here然后在“here”中搜索文件“.important”,然后转到“目录”并在树上搜索“.important”等等。我不想向下递减路径中的任何一点。 感谢

1 个答案:

答案 0 :(得分:1)

一旦你理解了bash中的字符串操作就足够了。

dest=/path/to/directory/here
curr=

# quote right-hand side to prevent interpretation as glob-style pattern
while [[ $curr != "$dest" ]]; do
  if [[ -e $curr/.important ]]; then
    printf 'Found ' >&2
    printf '%s\n' "$curr/.important"
  else
    printf '%s\n' "Not found at $curr" >&2
  fi
  rest=${dest#$curr/}  # strip $curr/ from $dest to get $rest
  next=${rest%%/*}     # strip anything after the first / from next
  [[ $next ]] || break # break if next is empty
  curr=$curr/$next     # otherwise, add next to curr and recur
done

有关此处使用的字符串扩展语法的更多信息,请参阅http://wiki.bash-hackers.org/syntax/pe

可替换地:

( set -f; cd /; IFS=/; for dir in $dest; do
    cd "$dir" || break
    if [ -e .important ]; then
      pwd
      break
    fi
  done )

关键点:

  • set -f禁用了globbing;否则,对于名为*
  • 的目录,这将表现得非常糟糕
  • IFS=/在扩展时设置字符串拆分以对/进行操作。
  • for dir in $dest 仅在上述两项操作完成后才安全。
  • break如果cd失败,则必须确保您的脚本实际位于其认为的目录中。

请注意,这是在子shell中(根据括号)完成的,以防止其对shell设置(set -fIFS=)的更改影响较大的脚本。这意味着您可以在$()中使用它并通过stdout将其输出读入shell变量,但是您无法在其中设置变量并期望该变量仍在父脚本中设置。