Skip to content

Instantly share code, notes, and snippets.

@yeiichi
Last active June 18, 2025 02:48
Show Gist options
  • Save yeiichi/f2288e49ed6794fa6cda84e3216195d1 to your computer and use it in GitHub Desktop.
Save yeiichi/f2288e49ed6794fa6cda84e3216195d1 to your computer and use it in GitHub Desktop.
Traverse the directory tree upwards to the marked directory
#!/usr/bin/env sh
# Traverse the directory tree upwards to the marked directory.
MARKER_DIR=".git" # Arbitrary directory like '.git', '.env', etc.
display_help() {
cat <<EOF
Usage: $(basename "$0") [OPTIONS]
Options:
--help Display this help message and exit.
Description:
This script is designed to be executed using the "source" command:
source $(basename "$0")
Purpose:
The script navigates upwards through the directory hierarchy from the current
working directory and stops when it finds a specific marker directory
(default: ".git"). Once the marker directory is found, the script changes the
current working directory to its parent directory, effectively placing the user
in the directory containing the marker.
Key Features:
- Traverse the directory tree upwards, checking each level for the marker directory.
- Automatically changes the shell's working directory to the parent of the marker directory.
- The marker directory can be customized by altering the MARKER_DIR variable
(default is ".git").
Examples:
1. To find the nearest ".git" directory and navigate to its parent:
source $(basename "$0")
2. To display this help message:
source $(basename "$0") --help
EOF
}
go_up_to_marker() {
current_dir=$PWD
while [ "${current_dir}" != "/" ]; do
marker_to_be_checked="${current_dir}/${MARKER_DIR}"
echo "Checking directory: ${current_dir}"
if [ -d "${marker_to_be_checked}" ]; then
printf "\033[93mDirectory found : %s\033[0m\n" "${marker_to_be_checked}"
cd "${current_dir}" || {
echo "Failed to cd into ${current_dir}"
exit 1
}
printf "\033[93m You are now in: %s\033[0m\n" "${current_dir}"
return 0
fi
current_dir=$(dirname "$current_dir")
done
printf "\033[93m%s not found up to root.\033[0m\n" "${MARKER_DIR}"
return 1
}
main() {
[ "$1" = "--help" ] || [ -L "$0" ] && display_help && exit 0
go_up_to_marker
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment