【问题标题】:How do I change directory (cd) to a directory where a specified file exists?如何将目录 (cd) 更改为存在指定文件的目录?
【发布时间】:2020-05-23 11:47:13
【问题描述】:

下面的代码是一个shell脚本find.sh。我在我的应用程序中包含指令,告诉用户从它所在的默认目录运行此脚本,因为它的目的是查看父目录并查看 Dockerfile 是否存在。

#!/bin/bash

FILE=../Dockerfile

if [ -f "$FILE" ]; then
  # Change to the parent directory.
  cd ..
fi

# Try stop a Docker container. This code could be anything. 
docker container stop container_name

但是,这有其局限性,因为它强制用户从自己的目录运行脚本,否则 cd .. 不会将目录更改为 Dockerfile 的预期位置。

如何修改此脚本,以便用户可以从任何目录运行它,并且它仍然可以找到并更改到 Dockerfile 目录?

【问题讨论】:

标签: linux bash shell docker ubuntu


【解决方案1】:

就像 Kapil 提到的,你可以使用find 命令。

#!/bin/bash

# Search for a file named Dockerfile in the path ../
# This will also go through the subdirectories as well.
FILE=$(find ../ -name Dockerfile)

if [ -f "$FILE" ]; then
  # Get the directory path from the file path.
  # Example:
  #   /path/to/file     <-- file path
  #   /path/to/         <-- directory path
  DIR=$(dirname "$FILE")
  cd "$DIR"
fi

【讨论】:

    【解决方案2】:

    有用的选择可能是有 2 个命令,第一个用于查找文件,第二个用于导航到其目录

    find ./ -name "Dockerfile.blabla"
    cd "$(dirname "$(!!)")"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多