简体   繁体   中英

How do I change directory (cd) to a directory where a specified file exists?

The code below is a shell script find.sh . I include instructions within my application that tells the user to run this script from default directory it is located in because its purpose is to look at the parent directory and see if a Dockerfile exists.

#!/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

However, this has its limitations as it forces the user to run the script from its own directory, as otherwise cd.. would not change directory to the intended location of the Dockerfile.

How can I modify this script so the user can run it from any directory and it still finds and changes to the Dockerfile directory?

Like Kapil mentioned, you can use the find command.

#!/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

the useful choice could be having 2 commands, 1st to find the file and 2nd to navigate to its directory

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM