Skip to content

Instantly share code, notes, and snippets.

@etiennecollin
Last active July 15, 2023 14:32
Show Gist options
  • Save etiennecollin/2ce1e563388533212606ae31ab5f72cd to your computer and use it in GitHub Desktop.
Save etiennecollin/2ce1e563388533212606ae31ab5f72cd to your computer and use it in GitHub Desktop.
This modified version of the cd command will recursively cd into directories that contain a single subdirectory. You may append this code to your shell config file (such as .zshrc, .bashrc, etc...).
function rcd {
# Check that number of arguments is 1
if [ $# -ne 1 ]; then
echo "Please input the path to a directory as the argument."
return 0
fi
# Store the given path as a variable
dirpath=$1
# Check that the path is a directory
if ! [[ -d $dirpath ]]; then
echo "Please input the path to a directory as the argument."
return 0
fi
# While $dirpath contains a single item...
while [ $(ls $dirpath | wc -l) -eq 1 ]; do
# If the item in the directory is also a directory
if [[ -d $dirpath/$(ls $dirpath) ]]; then
# Add it to the path to cd into
dirpath=$dirpath/$(ls $dirpath)
else
break
fi
done
# cd into the directories
cd $dirpath
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment