← Back to all snippets
BASH

Automate Git Clone and Node.js Dependency Installation

Streamline web project setup. This bash script automates cloning a Git repository and installing Node.js dependencies with npm or yarn, simplifying initial project setup for developers.

#!/bin/bash
REPO_URL=$1
PROJECT_DIR=$2

if [ -z "$REPO_URL" ]; then
    echo "Usage: $0 <repo_url> [project_directory]"
    exit 1
fi

if [ -z "$PROJECT_DIR" ]; then
    PROJECT_DIR=$(basename "$REPO_URL" .git)
fi

echo "Cloning repository: $REPO_URL into $PROJECT_DIR"
git clone "$REPO_URL" "$PROJECT_DIR"

if [ $? -eq 0 ]; then
    echo "Repository cloned successfully. Entering directory..."
    cd "$PROJECT_DIR"
    
    if [ -f "package.json" ]; then
        echo "package.json found. Installing Node.js dependencies..."
        if command -v yarn &> /dev/null; then
            yarn install
        elif command -v npm &> /dev/null; then
            npm install
        else
            echo "Neither yarn nor npm found. Please install one to proceed."
        fi
    else
        echo "No package.json found. Skipping Node.js dependency installation."
    fi
    echo "Setup complete for $PROJECT_DIR."
else
    echo "Error: Failed to clone repository $REPO_URL"
    exit 1
fi
How it works: This script automates the initial setup for a web project. It takes a Git repository URL as its first argument and an optional directory name as the second. It clones the specified repository, then checks if a `package.json` file exists. If found, it attempts to install Node.js dependencies using `yarn install` (if Yarn is installed) or falls back to `npm install`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs