【问题标题】:Find whether a directory exists by specifying only its partial name通过仅指定其部分名称来查找目录是否存在
【发布时间】:2013-06-17 06:47:18
【问题描述】:

我想通过将目录的部分名称作为参数来查找目录是否存在。即如果存在名称为 /home/directory 的目录,我想通过给出 /home/direc* 来查找它是否存在

有没有办法在 shell 脚本中做到这一点?

我尝试了以下方法但不起作用:

directory=/home/direc*
if [[ -d "$directory" ]]; then
        echo found;
else
echo not found
fi

【问题讨论】:

  • 如果 /home/direc* 匹配不止一次,即 /home/directory 和 /home/director 怎么办?我假设您想在脚本中实现制表符补全之类的功能?
  • 完全正确.. 基本上我需要检查 /usr/lib/jvm 中是否存在具有特定版本的 java 文件夹.. 存在许多 java 版本但我需要找到一个特定的但我不知道它的颠覆,所以我不能给出它的全名..
  • 你为什么使用 [[ -d "$directory" ]] 而不是 [ -d "$directory" ] ?
  • 读到双括号更快的地方

标签: shell


【解决方案1】:
directory=/home/direc*
for f in $directory
do
    if [ -d $f ]
    then
        echo $f
    fi
done

【讨论】:

    【解决方案2】:

    您可以使用“wc”来计算结果,并这样做:

    files=$(ls /home/dir* > /dev/null | wc -l)
    if [ **"$files" != "0"** ]
    then
    echo "Dir exists"
    else
    echo "Doesn't exist"
    fi
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 2017-10-19
      • 2022-09-29
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多