Skip to content

Instantly share code, notes, and snippets.

@MohamedElashri
Last active September 29, 2024 20:37
Show Gist options
  • Save MohamedElashri/bdc67a720e9e3c4287831799f94933c3 to your computer and use it in GitHub Desktop.
Save MohamedElashri/bdc67a720e9e3c4287831799f94933c3 to your computer and use it in GitHub Desktop.
Automate GitHub Repo Creation and Push with a Bash Function

This bash function automates the process of initializing a Git repository, creating a GitHub repository, and pushing your local files—all from the command line using the GitHub CLI (gh). It also disables wikis and issues for the created repo.

Add the following function to your .bashrc or .zshrc file:

create_and_push_repo() {
    if ! command -v gh &> /dev/null
    then
        echo "Error: GitHub CLI (gh) is not installed. Please install it first."
        return 1
    fi

    if [ -z "$1" ]; then
        echo "Usage: create_and_push_repo <repo-name> [--private]"
        return 1
    fi

    REPO_NAME=$1
    PRIVACY_FLAG="--public"

    if [ "$2" = "--private" ]; then
        PRIVACY_FLAG="--private"
    fi

    if ! git init; then
        echo "Error: Failed to initialize git repository."
        return 1
    fi

    if ! git add .; then
        echo "Error: Failed to add files to git repository."
        return 1
    fi

    if ! git commit -m "Initial commit"; then
        echo "Error: Failed to commit files."
        return 1
    fi

    if ! gh repo create "$REPO_NAME" $PRIVACY_FLAG --disable-wiki --disable-issues --source=. --remote=origin --push; then
        echo "Error: Failed to create GitHub repository and push files."
        return 1
    fi

    echo "Repository $REPO_NAME created and pushed successfully!"
}

After adding the function, reload your shell:

source ~/.bashrc
# or
source ~/.zshrc

Usage

  1. Create a public repository:

    create_and_push_repo my-repo
  2. Create a private repository:

    create_and_push_repo my-repo --private
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment