Last active
February 20, 2026 10:55
-
-
Save dineshr93/544427ffb1bf7f1e4c8d08841bfc95ed to your computer and use it in GitHub Desktop.
cdgit - clone a git repository and cd into the cloned directory automatically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # cdgit - clone a git repository and cd into the cloned directory automatically | |
| # | |
| # Usage: | |
| # cdgit clone <repo-url> [directory] | |
| # | |
| # Examples: | |
| # Just prepend to your normal git clone command with 'cd' | |
| # cdgit clone https://github.com/dineshr93/sq.git | |
| # - Clones the repo and cds into the folder named 'sq' | |
| # | |
| # cdgit clone https://github.com/dineshr93/sq.git myfolder | |
| # - Clones the repo into 'myfolder' and cds into 'myfolder' | |
| # | |
| # cdgit clone https://github.com/dineshr93/sq.git -b branch myfolder | |
| # - Clones the repo into 'myfolder' and cds into 'myfolder' | |
| # | |
| # If the clone fails, it will print an error and not cd. | |
| # | |
| # Add the below function to ~/bashrc and source ~/bashrc | |
| function cdgit() { | |
| if [ "$1" != "clone" ]; then | |
| echo "Usage: cdgit clone <repo-url> [directory]" | |
| return 1 | |
| fi | |
| # Capture directory list before clone | |
| before=$(ls -1d */ 2>/dev/null) | |
| # Run clone with all original arguments except "clone" | |
| git clone "${@:2}" | |
| if [ $? -ne 0 ]; then | |
| echo "git clone failed" | |
| return 1 | |
| fi | |
| # Capture directory list after clone | |
| after=$(ls -1d */ 2>/dev/null) | |
| # Find the new directory | |
| new_dir=$(comm -13 <(echo "$before" | sort) <(echo "$after" | sort) | head -n 1) | |
| # Remove trailing slash | |
| new_dir="${new_dir%/}" | |
| if [ -n "$new_dir" ]; then | |
| cd "$new_dir" || echo "Failed to cd into $new_dir" | |
| else | |
| echo "Could not determine cloned directory" | |
| fi | |
| } |
Author
Could also be a one liner: cdgit() { [ "$1" = "clone" ] && git "$@" && cd "$(basename "${@[-1]}" .git)"; }
the command handles below 2 cases too
-> git clone https://github.com/dineshr93/sq.git myfolder
-> git clone https://github.com/dineshr93/sq.git -b branch myfolder
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could also be a one liner: cdgit() { [ "$1" = "clone" ] && git "$@" && cd "$(basename "${@[-1]}" .git)"; }