gpt4 book ai didi

linux - 测试bash中是否至少存在一个名称前缀的目录

转载 作者:太空狗 更新时间:2023-10-29 12:09:11 25 4
gpt4 key购买 nike

我有一个带有用户输入名称的脚本,我想确定是否存在以该名称开头的目录。

这段代码看起来像:

runTest() {
if test -d "$name"*; then
echo "Directories starting with $name already exist"
fi
}

如果只有一个这样的目录,它工作正常:

name=foobar
rm -rf foobar*
mkdir foobar1
runTest # now the code will work

...但如果有多个匹配项,它不起作用:

name=foobar
rm -rf foobar*
mkdir foobar1 foobar2
runTest # now the code will emit an error: "test: too many arguments"

如何在不假设其中一个匹配项始终包含特定数字(如 1)的情况下使用任意数量的目录?

最佳答案

作为一个可行的(bash-only -- 不兼容/bin/sh)的例子,考虑:

if dirs=( "$name"*/ ) && [[ -d ${dirs[0]} ]]; then
echo "Directories starting with $name already exist"
fi
  • 数组赋值适用于任意数量的匹配
  • ...但数组中的第一个条目只有在 glob 成功扩展时才是有效目录(并且 glob 表达式中的尾随 / 阻止它扩展到任何内容 除了 目录,因此如果结果有任何目录,您就知道它扩展到的所有 元素都是目录)。

如果您还需要适用于 /bin/sh 的功能,请考虑以下功能:

directoriesExist() { [ -d "$1" ]; }
if directoriesExist "$name"*/; then
echo "Directories starting with $name already exist"
fi

这是有效的,因为匹配列表扩展到函数的参数列表,有效地替代数组。


因为 [ 是一个内置的 shell,这些基于 globbing 的方法比依赖外部工具的方法具有更低的常数因子成本,这将使它们总体上更快(除了一些极端情况,例如目录太大,最好在找到第一个匹配项后停止;其中 find .-name "$name*"-print -quit 可能有用)。

关于linux - 测试bash中是否至少存在一个名称前缀的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53605085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com