📝 TL;DR
Bash es un lenguaje de scripting utilizado en sistemas tipo Unix para automatizar tareas. Aprende a usarlo mientras automatizas operaciones de Git con un script que te permitirá realizar commits, push, cambiar de ramas y más, ahorrando tiempo y esfuerzo en tu flujo de trabajo diario.
🤔 ¿Por qué aprender Bash?
Bash es un lenguaje de scripting utilizado en sistemas tipo Unix para automatizar tareas. Su capacidad para ejecutar comandos del sistema y manipular archivos de forma sencilla lo convierte en una herramienta esencial para optimizar operaciones diarias.
Como caso práctico aprenderás a automatizar operaciones rutinarias de Git con Bash, como realizar commits, push, cambiar de ramas y más, mostrando cómo puedes ahorrar tiempo y esfuerzo en tu flujo de trabajo diario.
🔑 Conceptos básicos de Bash
Shebang (#!/bin/bash): Indica que el archivo debe ser ejecutado con Bash.
Variables: Almacenan valores y se acceden con $.
VARIABLE="Hello World"
echo $VARIABLE
Funciones: Bloques de código reutilizables.
function greeting() {
  echo "Hi!"
}
greeting
Condicionales (if, else): Ejecutan comandos basados en condiciones.
if [ "$USER" == "root" ]; then
  echo "You are root"
else
  echo "You are not root"
fi
Bucles (for, while): Repiten comandos hasta que se cumpla una condición.
for i in {1..5}; do
  echo "Number: $i"
done
while [ $i -le 5 ]; do
  echo "Number: $i"
  ((i++))
done
⚙️ Git Helper Script
Script: git-helper.sh
#!/bin/bash
show_menu() {
  echo "==================================="
  echo "          Git Helper Script        "
  echo "==================================="
  echo "1) Perform git pull"
  echo "2) Create a new branch"
  echo "3) Switch to an existing branch"
  echo "4) Add files and commit"
  echo "5) Show repository status (git status)"
  echo "6) Push to the current branch"
  echo "7) Show commit history (git log)"
  echo "8) Exit"
  echo "==================================="
}
git_pull() {
  echo "Performing git pull..."
  git pull
}
create_branch() {
  read -p "Enter the name of the new branch: " branch_name
  if git branch --list | grep -q "$branch_name"; then
    echo "Error: The branch '$branch_name' already exists."
    return
  fi
  echo "Creating and switching to branch $branch_name..."
  git checkout -b "$branch_name"
}
switch_branch() {
  branches=$(git branch)
  if [ -z "$branches" ]; then
    echo "No branches available in this repository."
    return
  fi
  echo "Available branches:"
  echo "$branches"
  read -p "Enter the name of the branch you want to switch to: " branch_name
  if ! git branch --list | grep -q "$branch_name"; then
    echo "Error: The branch '$branch_name' does not exist."
    return
  fi
  echo "Switching to branch $branch_name..."
  git checkout "$branch_name"
}
git_commit() {
  while true; do
    git status
    read -p "Which files do you want to add? (use . for all or 'exit' to cancel): " files
    if [[ "$files" == "exit" ]]; then
      echo "Operation canceled."
      return
    fi
    git add "$files"
    read -p "Enter the commit message: " commit_message
    git commit -m "$commit_message"
    echo "Commit completed."
    break
  done
}
git_status() {
  echo "Showing repository status..."
  git status
}
git_push() {
  echo "Pushing to branch $branch..."
  git push origin "$branch"
}
git_log() {
  echo "Recent commit history:"
  git log --oneline --graph --decorate -10
}
check_git_repo() {
  if [ ! -d .git ]; then
    echo "Error: This does not appear to be a Git repository."
    exit 1
  fi
}
main() {
  check_git_repo
  while true; do
    show_menu
    read -p "Select an option: " choice
    case $choice in
      1) git_pull ;;
      2) create_branch ;;
      3) switch_branch ;;
      4) git_commit ;;
      5) git_status ;;
      6) git_push ;;
      7) git_log ;;
      8) echo "Exiting..."; exit 0 ;;
      *)
        echo "Invalid option. Please try again."
        continue
        ;;
    esac
    break
  done
}
main
Resultado:
Ejecución:
- 
Guarda el script como git-helper.shy hazlo ejecutable:
 chmod +x git-helper.sh
- 
(Opcional) Colócalo en un directorio que esté en tu PATH (por ejemplo, /usr/local/bin) para usarlo globalmente:
 mv git-helper.sh /usr/local/bin/git-helper
- 
Ejecútalo: 
 git-helper
🛠️ Paso a paso
Paso 1: Crear un menú principal
El primer paso es crear un menú principal con las opciones disponibles.
show_menu() {
  echo "==================================="
  echo "          Git Helper Script        "
  echo "==================================="
  echo "1) Perform git pull"
  echo "2) Create a new branch"
  echo "3) Switch to an existing branch"
  echo "4) Add files and commit"
  echo "5) Show repository status (git status)"
  echo "6) Push to the current branch"
  echo "7) Show commit history (git log)"
  echo "8) Exit"
  echo "==================================="
}
Explicación:
- Utilizamos echopara mostrar mensajes en la consola.
- El menú se muestra con las opciones disponibles.
Paso 2: Validar si es un repositorio Git
Antes de realizar cualquier operación de Git, es importante verificar si el directorio actual es un repositorio Git.
check_git_repo() {
  if [ ! -d .git ]; then
    echo "Error: This does not appear to be a Git repository."
    exit 1
  fi
}
Explicación:
- Verificamos con -d .gitsi existe un directorio.giten el directorio actual.
- Si no es un repositorio Git, mostramos un mensaje de error y salimos del script con exit 1(código de error).
Paso 3: Crear funciones para las operaciones de Git
Cada función realiza una operación específica de Git. A continuación, se muestran algunas de las funciones disponibles:
Crear una nueva rama
create_branch() {
  read -p "Enter the name of the new branch: " branch_name
  if git branch --list | grep -q "$branch_name"; then
    echo "Error: The branch '$branch_name' already exists."
  fi
  echo "Creating and switching to branch $branch_name..."
  git checkout -b "$branch_name"
}
Explicación:
- Con read -pleemos la entrada del usuario para el nombre de la nueva rama y almacenamos el valor enbranch_name.
- Usamos git branch --listpara listar las ramas existentes ygrep -qpara buscar si la rama almacenada enbranch_nameexiste en la lista.- Si la rama ya existe, mostramos un mensaje de error y salimos de la función.
 
- Si la rama no existe, creamos y cambiamos a la nueva rama con git checkout -b.
Cambiar a una rama existente
switch_branch() {
  branches=$(git branch)
  if [ -z "$branches" ]; then
    echo "No branches available in this repository."
    return
  fi
  echo "Available branches:"
  echo "$branches"
  read -p "Enter the name of the branch you want to switch to: " branch_name
  if ! git branch --list | grep -q "$branch_name"; then
    echo "Error: The branch '$branch_name' does not exist."
    return
  fi
  echo "Switching to branch $branch_name..."
  git checkout "$branch_name"
}
Explicación:
- Almacena las ramas existentes en la variable branches.
- Con -zverificamos si la variablebranchesestá vacía.- Si no hay ramas disponibles, mostramos un mensaje y salimos de la función.
 
- Mostramos las ramas disponibles y leemos la entrada del usuario para la rama a la que desea cambiar.
- Usamos git branch --listygrep -qpara verificar si la rama existe.- Si la rama no existe, mostramos un mensaje de error y salimos de la función.
 
- Cambiamos a la rama seleccionada con git checkout.
📂 Repositorio del proyecto
Para seguir este ejemplo de automatización de operaciones de Git con Bash, puedes clonar o explorar el repositorio asociado.
Repositorio: https://github.com/israoo/git-helper-bash
Este repositorio contiene:
- Script git-helper.shcon las funciones para automatizar operaciones de Git.
- Instrucciones detalladas en el archivo README.md sobre cómo configurar y ejecutar el script paso a paso.
🔗 Referencias/Extras
🚀 ¿Qué sigue?
¿Ya estás usando git tags o submódulos? Agrega estas funcionalidades a tu script para mejorar aún más tu flujo de trabajo con Git. ¡Coméntalo y comparte tus ideas!
 
 
              

 
    
Top comments (0)