首页 > 解决方案 > 在bash中搜索多个目录中的文件

问题描述

我有这样的结构:

basedir -> 187382 -> name1 -> name1.keytab
basedir -> 049328 -> name2 -> name2.keytab
basedir -> 233432 -> name3 -> name3.keytab
basedir -> 234343 -> name4 -> name4.keytab
...

数字不同,我不知道。

在 bash 脚本中,我想说:

export X="basedir/*/$name/$name.keytab"

我应该写什么而不是星星?或者,如果不存在这样的符号......我如何在 basedir 的每个文件夹中搜索 $name.keytab?

标签: bashshell

解决方案


将您的 glob 扩展为array,而不是 string 变量,留下未加*引号的:

#!/usr/bin/env bash
[[ $BASH_VERSION ]] || { echo "ERROR: Shell is not bash" >&2; exit 1; }
shopt -s nullglob  # allow a glob to expand to an empty list if nothing matches

keytabs=( "basedir/"*"/$name/$name.keytab" )
case ${#keytabs[@]} in
  0) echo "ERROR: no keytab found for $name" >&2; exit 1;;
  1) true;;
  *) echo "ERROR: ${#keytabs[@]} keytabs found for $name; expected only one" >&2; exit 1;;
esac

# assign the first/only keytab we matched to an exported string variable.
X=${keytabs[0]}; export X

# for debugging purposes, print the definition of X so it's visible that we exported it
declare -p X >&2

推荐阅读