Skip to content

Instantly share code, notes, and snippets.

@GNOMES
Last active October 29, 2025 03:03
Show Gist options
  • Select an option

  • Save GNOMES/6bf65926648e260d8023aebb9ede9573 to your computer and use it in GitHub Desktop.

Select an option

Save GNOMES/6bf65926648e260d8023aebb9ede9573 to your computer and use it in GitHub Desktop.
cd backwards to named directoy in current path
# Add to ~/.bashrc
# jump backwards from cwd path
dc() {
cd "${PWD%/$1/*}/$1/" 2>/dev/null || echo "Directory not found: $1"
}
# Function to add tab completion to dc
_dc_complete() {
IFS='/' read -ra dirs <<<"$(pwd)"
local dir_names=("${dirs[@]:1}")
COMPREPLY=()
for dir in "${dir_names[@]}"; do
[[ $dir == ${COMP_WORDS[COMP_CWORD]}* ]] && COMPREPLY+=("$dir")
done
}
complete -F _dc_complete dc
@GNOMES
Copy link
Author

GNOMES commented Jan 3, 2025

Using this instead of repetitive cd ../../.. for going backwards from current directory.

Example:

$ mkdir -p /foo/bar/batz/example/directory      # create test folder structure
$ cd /foo/bar/batz/example/directory            # navigate somewhere into folder structure
$ dc bar && pwd                                 # cd back to /foo/bar and list current directory as evidence
/foo/bar

@GNOMES
Copy link
Author

GNOMES commented Oct 23, 2025

Revised parent gist to a pure bash version. Older version using sed:

dc() {

    cd "$(pwd | sed "s|$1\/.*|$1\/|")" || echo "Directory not found: $1"

} 

@sudobash1
Copy link

@GNOMES Thanks for this. It is pretty slick.

I try to keep track of the source and license of all the snippets I put in my bashrc. Is there a license I can put down for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment