Skip to content

Instantly share code, notes, and snippets.

@deanhouseholder
Created January 20, 2022 00:51
Show Gist options
  • Save deanhouseholder/b43de34bf831206c0db0f091f309ac94 to your computer and use it in GitHub Desktop.
Save deanhouseholder/b43de34bf831206c0db0f091f309ac94 to your computer and use it in GitHub Desktop.
Bash enhanced 'cd' replacement
# Replace cd functionality to use pushd instead. If file is given, open in default editor.
#
# You can define an array of keyword-based pre-defined directories which will work anywhere
# Examples:
# "cd bin" will take you to ~/bin/
# "cd logs" will take you to /var/log/apache2/
# Setup:
# Inside your local_env.sh script, define them in this manner:
# cd_array=(
# 'bin'='/root/bin'
# 'www'='/var/www'
# 'logs'='/var/log/apache2'
# 'apache'='/etc/apache2/sites-available'
# )
function cd(){
if [[ "$#" == "0" ]]; then
pushd $HOME 1>/dev/null
elif [[ -f "$1" ]]; then
$EDITOR "$1"
elif [[ "$1" =~ ^\-+$ ]]; then
# support multiple dashes and go back through dir stack for each one
bd ${#1} 1>/dev/null
elif [[ -d "$1" ]]; then
pushd "$1" 1>/dev/null
else
# If an array called $cd_array is defined, loop through it and check for shortcuts
# matching $1 to jump to a pre-defined location instead
for i in "${cd_array[@]}"; do
keyword=$(echo "$i" | cut -d= -f1)
path=$(echo "$i" | cut -d= -f2)
test "$1" == "$keyword" && local newdir="$path" && break
done
if [[ ! -z "$newdir" ]]; then
pushd "$newdir" 1>/dev/null
else
printf "cd $1: No such file or directory\n"
fi
fi
}
# Display a list of cd aliases
# TODO: enhance with fzf
alias cdlist='printf "\nList of cd aliases:\n\n" && printf "%s\n" ${cd_array[@]} | column -t -s= && echo'
# Add a "back directory" function to change back (with popd) any number of directories
function bd(){
if [[ -z "$1" ]]; then
popd &>/dev/null
else
for i in $(seq $1); do
popd &>/dev/null
done
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment