BASH

Automate Git Clone and Dependency Install

A bash script to automate cloning a Git repository and installing common project dependencies (npm, Composer), ideal for new project setups.

#!/bin/bash

REPO_URL=$1
TARGET_DIR=$2

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

if [ -z "$TARGET_DIR" ]; then
  # Extract repo name from URL to use as target directory
  TARGET_DIR=$(basename "$REPO_URL" .git)
fi

echo "Cloning $REPO_URL into $TARGET_DIR..."
git clone "$REPO_URL" "$TARGET_DIR"

if [ $? -ne 0 ]; then
  echo "Error: Failed to clone repository."
  exit 1
fi

cd "$TARGET_DIR" || { echo "Error: Could not change directory to $TARGET_DIR"; exit 1; }

echo "Installing dependencies in $TARGET_DIR..."

# Check for Node.js dependencies
if [ -f "package.json" ]; then
  echo "  - Running npm install..."
  npm install
  if [ $? -ne 0 ]; then echo "Warning: npm install failed."; fi
fi

# Check for PHP dependencies
if [ -f "composer.json" ]; then
  echo "  - Running composer install..."
  composer install --no-dev --optimize-autoloader
  if [ $? -ne 0 ]; then echo "Warning: composer install failed."; fi
fi

echo "Project setup complete for $TARGET_DIR."
How it works: This script streamlines the initial setup of a web project. It takes a Git repository URL and an optional target directory, clones the repository, and then navigates into the new directory. It intelligently checks for `package.json` (Node.js/npm) and `composer.json` (PHP/Composer) files, running the appropriate dependency installation commands if found. This saves time and ensures consistency when setting up multiple projects or development environments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs