Created
October 20, 2024 03:01
-
-
Save anonimitoraf/98575516dea1abf48a27172da91d333f to your computer and use it in GitHub Desktop.
bash util: cdd - cd backwards recursively until it finds a matching parent dir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This goes to the closest ancestor dir that matches specified name | |
| cdd(){ | |
| depth=$(pwd | tr -dc '/' | wc -c) | |
| for ((d=0;d<=depth;d++)); do | |
| [ $d -eq 0 ] && search_dir="." || search_dir=$(printf '../%.0s' $(seq 1 $d)) | |
| res=( ) | |
| while IFS= read -r -d '' item; do | |
| res+=( "$item" ) | |
| done < <(find $search_dir -mindepth 1 -maxdepth 1 -type d -name "$1" -print0) | |
| if [ ${#res[@]} -eq 0 ]; then | |
| continue | |
| elif [ ${#res[@]} -eq 1 ]; then | |
| t="$res" | |
| elif [ ${#res[@]} -gt 1 ]; then | |
| select t in "${res[@]}"; do | |
| break | |
| done | |
| fi | |
| echo "$t" | |
| cd "$t" && return || { echo "Unknown Error"; return; } | |
| done | |
| echo "Not found" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment