Created
July 31, 2023 01:14
-
-
Save xebecnan/4f91e65f4e399559b27a9b4df7f99d0a to your computer and use it in GitHub Desktop.
This file contains 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
# from https://unix.stackexchange.com/a/740187/580914 | |
# add to your .bashrc: | |
## cdf -- cd to frequent directories | |
function cdf() { | |
# Use awk to extract the directories from the history, using null characters as the separator | |
DIRS=$(history | tr '\n' '\0' | awk -v RS='\0' '$2 == "cd" && !/\$DIR/ { $1=""; $2=""; sub("^[[:space:]]*", ""); print }' | grep -v -P -C 5 'cd.*$DIR' | sort | uniq -c | sort -rn | head -n 12 | awk '{$1=""; sub("^[[:space:]]*", ""); print }') | |
# Filter out directories that don't exist and parent directories | |
VALID_DIRS=() | |
while IFS= read -r -d '' DIR; do | |
if [ -d "$(eval echo "$DIR")" ] && [[ "$DIR" != ".." && "$DIR" != */.. ]]; then | |
VALID_DIRS+=("$DIR") | |
fi | |
done < <(echo "$DIRS" | tr '\n' '\0' ) | |
if (( ${#VALID_DIRS[@]} == 0 )) ; then | |
echo "No directories in history." | |
return 1 | |
fi | |
# Use select to create a menu of the directories | |
PS3="Choose a directory to cd to: " | |
select DIR in "${VALID_DIRS[@]}"; do | |
if [ -z "$DIR" ]; then | |
echo "Invalid choice." | |
else | |
cd "$(eval echo "$DIR")" && history -s "cd $DIR" # cd and add the cd command to the history | |
break | |
fi | |
done | |
} | |
#### | |
# This is how the output looks like in real life: | |
# | |
# ~$ cdf | |
# 1) /home/maybit/junk/code/python/django/getting_started | |
# 2) /home/maybit/Music | |
# 3) /home/maybit/junk/xwiki/xwiki-platform-distribution-flavor-jetty-hsqldb-15.0-rc-1 | |
# [...] | |
# 10) /home/maybit/Downloads | |
# Choose a directory to cd to: 1 | |
# ~/junk/code/python/django/getting_started$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment