Skip to content

Instantly share code, notes, and snippets.

@lcarva
Created February 25, 2026 19:27
Show Gist options
  • Select an option

  • Save lcarva/52d75165cd918ebacc6e85321994f2f6 to your computer and use it in GitHub Desktop.

Select an option

Save lcarva/52d75165cd918ebacc6e85321994f2f6 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -euo pipefail
# Default base directory for cloning repositories
BASE_DIR="${GIT_SCLONE_BASE:-$HOME/src}"
# Check if URL is provided
if [ -z "$1" ]; then
echo "Usage: git-sclone <repository-url>"
echo "Example: git-sclone https://github.com/lcarva/festoji"
echo ""
echo "Set GIT_SCLONE_BASE to change the base directory (default: ~/src)"
exit 1
fi
REPO_URL="$1"
# Parse the repository URL to extract host, owner, and repo name
# Handle both HTTPS and SSH formats
if [[ "$REPO_URL" =~ ^https?://([^/]+)/([^/]+)/([^/]+?)(\.git)?$ ]]; then
# HTTPS format: https://github.com/owner/repo or https://github.com/owner/repo.git
HOST="${BASH_REMATCH[1]}"
OWNER="${BASH_REMATCH[2]}"
REPO="${BASH_REMATCH[3]}"
elif [[ "$REPO_URL" =~ ^git@([^:]+):([^/]+)/([^/]+?)(\.git)?$ ]]; then
# SSH format: git@github.com:owner/repo or git@github.com:owner/repo.git
HOST="${BASH_REMATCH[1]}"
OWNER="${BASH_REMATCH[2]}"
REPO="${BASH_REMATCH[3]}"
else
echo "Error: Could not parse repository URL: $REPO_URL"
echo "Supported formats:"
echo " - https://github.com/owner/repo"
echo " - git@github.com:owner/repo"
exit 1
fi
# Strip .git suffix if present
REPO="${REPO%.git}"
# Construct the target directory
TARGET_DIR="$BASE_DIR/$HOST/$OWNER/$REPO"
# Check if directory already exists
if [ -d "$TARGET_DIR" ]; then
echo "Error: Directory already exists: $TARGET_DIR"
exit 1
fi
# Create parent directory if needed
mkdir -p "$(dirname "$TARGET_DIR")"
# Clone the repository
echo "Cloning $REPO_URL to $TARGET_DIR..." >&2
git clone "$REPO_URL" "$TARGET_DIR"
echo "$TARGET_DIR"
@lcarva
Copy link
Author

lcarva commented Feb 25, 2026

Drop this somewhere in $PATH to make git clone-structured available.

Also, you can add this to your .bashrc to clone and cd into the directory in one command, e.g. clone <git-url>:

clone() {                                                                                              
  local dir                                                                                            
  dir=$(git clone-structured "$@") && cd "$dir"                                                        
}   

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