Skip to content

Instantly share code, notes, and snippets.

@Bhupesh-V
Created August 13, 2020 09:32
Show Gist options
  • Save Bhupesh-V/7859aec678386c9e5ae9517c63ccfdda to your computer and use it in GitHub Desktop.
Save Bhupesh-V/7859aec678386c9e5ae9517c63ccfdda to your computer and use it in GitHub Desktop.
smart cd - Change directories smartly [v2]
scd() {
# [s]mart cd : find absolute paths & automatically switch to them
if [[ $1 != "" ]]; then
case $1 in
[".."]* ) cd .. || exit;;
["-"]* ) cd - || exit;;
["/"]* ) cd / || exit;;
* ) while read -r value; do
files+=($value)
done < <( locate -e -r "/$1$" | grep "$HOME" )
if [[ ${#files} == 0 ]]; then
# do loose search
while read -r value; do
files+=($value)
done < <( locate -e -b -r "$1" | grep "$HOME" )
fi
for file_match in "${files[@]}"; do
if [[ -d $file_match ]]; then
printf "%s\n" "Hit 🎯: $file_match"
cd "$file_match" || exit
fi
done
unset files ;;
esac
else
cd "$HOME" || exit
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment