Skip to content

Instantly share code, notes, and snippets.

@Adam13531

Adam13531/ccd.sh

Created Aug 28, 2019
Embed
What would you like to do?
Adam13531's "CCD" command for Unix/Linux
# Allow for quick navigation of your filesystem.
# Example usage:
# ccd ~ Co sr stu
# This would move you to the folder ~/Code/src/stuff because it's translated as:
# cd ~
# cd Co
# cd Co* (this is tried because "Co" doesn't exist)
# cd sr
# cd sr*
# etc.
#
# Other features:
# * "..." and "...." can be used to go up multiple directories at a time.
# * If your directory can't be found, this will fall back to case-insensitivity.
function ccd() {
# Iterate through each argument
for arg in "$@"
do
if [[ "$arg" == "..." ]]; then
# Go up 2 directories
cd ../..
elif [[ "$arg" == "...." ]]; then
# Go up 3 directories
cd ../../..
elif [[ "$arg" == "....." ]]; then
# Go up 4 directories
cd ../../../..
elif [[ -d "$arg" ]]; then
# If this directory explicitly exists, navigate to it.
cd "$arg"
else
# Try $arg* so that "co" will match "code". To do this, we do "ls"
# and see if it prints this error:
# "ls: Applica*: No such file or directory"
local outputWithStar="$(ls $arg* 2>&1)"
# NOTE Mon 12/14/2015 - 10:03 PM
# Put quotes around "$outputWithStar" for Bash versions > 3.1.
if [[ "$outputWithStar" =~ ^ls\:\ $arg ]]; then
# "arg*" didn't exist, so fall back to case-insensitivity.
local firstCaseInsensitiveMatch=`(ls|grep -i "^$arg"|head -1)`
if [[ "$firstCaseInsensitiveMatch" == "" ]]; then
colorize "^r*** \"$arg\" does not exist. Printing directories: ***\n"
# Turn off coloring for this particular grep command so that
# we don't see the letter 'd' in red each time.
ls -l | egrep '^d' --color=never
printf "\n"
return
else
cd "$firstCaseInsensitiveMatch"
fi
else
local star="*"
# Only $arg goes in quotes to cover an edge-case where there's a
# directory with a space like "Hello World" and you type ccd
# "Hello W".
cd "$arg"$star
fi
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment