BASH
📁 NAVEGACIÓN Y ARCHIVOS
Section titled “📁 NAVEGACIÓN Y ARCHIVOS”pwd # Directorio actualls # Listar archivosls -la # Listar todos (incluye ocultos) con detallescd ~ # Ir a homecd - # Ir al directorio anteriormkdir nombre # Crear directoriotouch archivo.txt # Crear archivo vacíocp origen destino # Copiar archivocp -r origen destino # Copiar directoriomv origen destino # Mover/Renombrarrm archivo.txt # Eliminar archivorm -r directorio # Eliminar directoriorm -rf directorio # Eliminar forzado (¡CUIDADO!)find . -name "*.txt" # Buscar archivos📝 MANIPULACIÓN DE TEXTO
Section titled “📝 MANIPULACIÓN DE TEXTO”cat archivo.txt # Ver contenidocat > archivo.txt # Crear/escribir (Ctrl+D para salir)cat >> archivo.txt # Añadir al finalless archivo.txt # Ver con paginaciónhead -n 10 archivo.txt # Primeras 10 líneastail -n 10 archivo.txt # Últimas 10 líneastail -f archivo.txt # Seguir actualizaciones (logs)grep "texto" archivo # Buscar textogrep -r "texto" ./ # Buscar recursivosed 's/old/new/g' file # Reemplazar textoawk '{print $1}' file # Imprimir primera columnawc -l archivo.txt # Contar líneassort archivo.txt # Ordenaruniq archivo.txt # Líneas únicas🔧 PERMISOS
Section titled “🔧 PERMISOS”chmod 755 archivo # rwxr-xr-xchmod +x archivo.sh # Hacer ejecutablechown usuario archivo # Cambiar propietariochgrp grupo archivo # Cambiar grupo🚀 PROCESOS Y SISTEMA
Section titled “🚀 PROCESOS Y SISTEMA”ps aux # Procesos en ejecuciónps aux | grep bash # Buscar procesokill PID # Terminar procesokill -9 PID # Forzar terminacióntop # Monitor de procesos (presiona q para salir)htop # Mejor que top (instalar si no)df -h # Espacio en discodu -sh * # Tamaño de archivos/carpetasfree -h # Memoria RAMuptime # Tiempo encendidowhoami # Usuario actualhostname # Nombre del equipouname -a # Información del sistema🔗 VARIABLES Y EXPANSIONES
Section titled “🔗 VARIABLES Y EXPANSIONES”nombre="Juan" # Asignar variableecho $nombre # Usar variableecho ${nombre} # Lo mismo (más seguro)echo "Hola $nombre" # Con comillas doblesecho 'Hola $nombre' # Con comillas simples (no expande)
# Expansión de comandosfecha=$(date)fecha=`date` # Sintaxis antigua
# Expansión aritméticasuma=$((2 + 2))
# Variables de entornoexport PATH=$PATH:/nuevo/direcho $PATHecho $HOME🔀 REDIRECCIÓN Y PIPES
Section titled “🔀 REDIRECCIÓN Y PIPES”comando > archivo.txt # Redirigir salida (sobrescribe)comando >> archivo.txt # Redirigir salida (añade)comando 2> errores.txt # Redirigir errorescomando &> salida.txt # Redirigir todocomando < archivo.txt # Entrada desde archivo
# Pipes (encadenar comandos)ls -la | grep ".txt" # Filtrarcat archivo | sort | uniq # Procesar🧠 CONDICIONALES
Section titled “🧠 CONDICIONALES”if [ "$a" -eq "$b" ]; then echo "Son iguales"elif [ "$a" -gt "$b" ]; then echo "a es mayor"else echo "a es menor"fi
# Operadores numéricos: -eq, -ne, -lt, -le, -gt, -ge# Operadores de strings: =, !=, -z (vacío), -n (no vacío)# Operadores de archivos: -f (existe), -d (directorio), -r (lectura), -w (escritura), -x (ejecutable)
# Operadores lógicos[ "$a" -gt 10 ] && [ "$b" -lt 5 ] # AND[ "$a" -gt 10 ] || [ "$b" -lt 5 ] # OR! [ "$a" -gt 10 ] # NOT🔄 BUCLES
Section titled “🔄 BUCLES”# For con listafor i in 1 2 3 4 5; do echo "Número: $i"done
# For con rangofor i in {1..10}; do echo $idone
# For con secuenciafor ((i=0; i<10; i++)); do echo $idone
# For con archivosfor archivo in *.txt; do echo "Procesando $archivo"done
# Whilewhile [ "$i" -lt 10 ]; do echo $i ((i++))done
# Untiluntil [ "$i" -ge 10 ]; do echo $i ((i++))done🛠️ FUNCIONES
Section titled “🛠️ FUNCIONES”# Definir funciónmi_funcion() { echo "Hola $1" return 0}
# O con functionfunction mi_funcion { echo "Hola $1"}
# Llamarmi_funcion "Mundo"
# Parámetros: $1, $2, ..., $@ (todos), $# (cantidad)🎯 COMANDOS ÚTILES
Section titled “🎯 COMANDOS ÚTILES”echo "texto" # Imprimirprintf "Formato %s\n" "texto" # Imprimir con formatosleep 5 # Esperar 5 segundosdate # Fecha y horawho # Usuarios conectadoshistory # Historial de comandos!! # Último comando!100 # Ejecutar comando #100 del historialalias # Ver aliaswhich comando # Ubicación del comandotype comando # Tipo de comandoman comando # Manualcomando --help # Ayuda📋 TRUCOS ÚTILES
Section titled “📋 TRUCOS ÚTILES”# Comentarios# Esto es un comentario
# Comandos encadenadoscmd1 && cmd2 # Ejecuta cmd2 si cmd1 éxitocmd1 || cmd2 # Ejecuta cmd2 si cmd1 fallacmd1 ; cmd2 # Ejecuta ambos siempre
# Sustitución de comandosecho "Fecha: $(date)"echo "Fecha: `date`" # Sintaxis antigua
# Expansión de llavesecho {1..10} # 1 2 3 4 5 6 7 8 9 10echo {a..z} # a b c ... zmkdir {dir1,dir2,dir3} # Crea 3 directorios
# Heredoccat << EOFEsto es untexto multilíneaEOF
# Ver salida y guardarcomando | tee archivo.txt
# Ejecutar en backgroundcomando &
# Salir del scriptexit 0 # Éxitoexit 1 # Error🔗 GENERAR ALIAS EN BASH
Section titled “🔗 GENERAR ALIAS EN BASH”ALIAS TEMPORALES
Section titled “ALIAS TEMPORALES”# Crear alias (válido solo en la sesión actual)alias ll='ls -la'alias gs='git status'alias gp='git pull'alias ..='cd ..'alias ...='cd ../..'
# Ver todos los aliasalias
# Eliminar aliasunalias llALIAS PERMANENTES
Section titled “ALIAS PERMANENTES”Opción 1: Archivo ~/.bashrc (Recomendado)
Section titled “Opción 1: Archivo ~/.bashrc (Recomendado)”# Abrir el archivonano ~/.bashrc
# Añadir al final:# =============================================# MIS ALIAS PERSONALES# =============================================alias ll='ls -la'alias la='ls -A'alias l='ls -CF'alias ..='cd ..'alias ...='cd ../..'alias cls='clear'alias gs='git status'alias ga='git add'alias gc='git commit'alias gp='git push'alias gl='git log --oneline --graph'alias gd='git diff'alias ports='netstat -tulanp'alias myip='curl ifconfig.me'alias df='df -h'alias du='du -h'alias free='free -h'alias psg='ps aux | grep'alias mkdir='mkdir -pv' # Crear directorios con -p y verbosealias cp='cp -iv' # Interactivo y verbosealias mv='mv -iv' # Interactivo y verbosealias rm='rm -i' # Interactivo (¡cuidado!)alias please='sudo $(history -p !!)' # Repetir con sudoalias update='sudo apt update && sudo apt upgrade -y' # Ubuntu/Debianalias reload='source ~/.bashrc' # Recargar bashrc
# Guardar y salir (Ctrl+X, Y, Enter)
# Recargar configuraciónsource ~/.bashrc# o. ~/.bashrcOpción 2: Archivo ~/.bash_aliases (Más organizado)
Section titled “Opción 2: Archivo ~/.bash_aliases (Más organizado)”# Crear archivo separadonano ~/.bash_aliases
# Añadir alias (mismo formato que arriba)
# En ~/.bashrc añadir (si no existe):if [ -f ~/.bash_aliases ]; then . ~/.bash_aliasesfi
# Recargarsource ~/.bashrcALIAS CON ARGUMENTOS (Funciones)
Section titled “ALIAS CON ARGUMENTOS (Funciones)”# Los alias no aceptan argumentos directamente, usar funciones
# En ~/.bashrc o ~/.bash_aliases:# Buscar archivos por nombrefindname() { find . -name "*$1*"}
# Crear y entrar en directoriomkcd() { mkdir -p "$1" && cd "$1"}
# Extraer cualquier archivo comprimidoextract() { if [ -f "$1" ]; then case "$1" in *.tar.bz2) tar xjf "$1" ;; *.tar.gz) tar xzf "$1" ;; *.bz2) bunzip2 "$1" ;; *.rar) unrar e "$1" ;; *.gz) gunzip "$1" ;; *.tar) tar xf "$1" ;; *.tbz2) tar xjf "$1" ;; *.tgz) tar xzf "$1" ;; *.zip) unzip "$1" ;; *.Z) uncompress "$1" ;; *.7z) 7z x "$1" ;; *) echo "'$1' no se puede extraer" ;; esac else echo "'$1' no es un archivo válido" fi}
# Backupsbackup() { cp "$1" "$1.bak"}
# Ir al directorio de proyectos (ejemplo)work() { cd ~/projects/"$1"}EJEMPLOS PRÁCTICOS DE ALIAS
Section titled “EJEMPLOS PRÁCTICOS DE ALIAS”# ============ NAVEGACIÓN ============alias ..='cd ..'alias ...='cd ../..'alias ....='cd ../../..'alias ~='cd ~'alias -='cd -'
# ============ LISTAR ARCHIVOS ============alias ll='ls -alF'alias la='ls -A'alias l='ls -CF'alias lr='ls -ltr' # Ordenar por fechaalias lh='ls -lSh' # Ordenar por tamaño
# ============ GIT ============alias g='git'alias gs='git status'alias ga='git add'alias gaa='git add --all'alias gc='git commit -m'alias gcm='git commit -m'alias gp='git push'alias gl='git pull'alias gd='git diff'alias gco='git checkout'alias gb='git branch'alias gm='git merge'alias glog='git log --oneline --graph --decorate'
# ============ SISTEMA ============alias ports='netstat -tulanp'alias myip='curl -s ifconfig.me'alias ping='ping -c 5'alias cls='clear'alias path='echo $PATH | tr ":" "\n"' # Mostrar PATH en líneasalias grep='grep --color=auto'alias mkdir='mkdir -pv'
# ============ SEGURIDAD ============alias rm='rm -i' # Confirmar antes de borraralias cp='cp -iv' # Interactivo y verbosealias mv='mv -iv' # Interactivo y verbosealias ln='ln -iv' # Interactivo y verbose
# ============ APT (Ubuntu/Debian) ============alias upd='sudo apt update'alias upg='sudo apt upgrade -y'alias ins='sudo apt install'alias rem='sudo apt remove'alias search='apt search'alias purge='sudo apt purge'alias autoremove='sudo apt autoremove'
# ============ DOCKER ============alias dps='docker ps'alias dpsa='docker ps -a'alias di='docker images'alias drm='docker rm'alias drmi='docker rmi'alias dexec='docker exec -it'alias dlogs='docker logs -f'RECARGAR ALIAS SIN REINICIAR
Section titled “RECARGAR ALIAS SIN REINICIAR”# Después de modificar ~/.bashrc o ~/.bash_aliases:source ~/.bashrc# o. ~/.bashrc
# Solo recargar alias:source ~/.bash_aliases # Si usas archivo separadoVER ALIAS ACTIVOS
Section titled “VER ALIAS ACTIVOS”# Ver todosalias
# Ver alias específicoalias ll
# Buscar aliasalias | grep git
# Mostrar con formatoalias | sortELIMINAR ALIAS
Section titled “ELIMINAR ALIAS”# Temporal (sesión actual)unalias ll
# Eliminar alias personalizadounalias ll
# Si está en ~/.bashrc, eliminar la línea y recargar# source ~/.bashrc después de editar🎯 MEJORES PRÁCTICAS
Section titled “🎯 MEJORES PRÁCTICAS”- Usar nombres cortos pero descriptivos
- Documentar alias complejos con comentarios
- No sobrescribir comandos importantes sin precaución
- Agrupar por categoría (git, navegación, sistema, etc.)
- Usar funciones para alias con argumentos
- Mantener ~/.bash_aliases separado para mejor organización
- Hacer backups de tus configuraciones
📚 RECURSOS ADICIONALES
Section titled “📚 RECURSOS ADICIONALES”# Ayuda integradahelp [comando] # Comandos built-inman [comando] # Manual completoinfo [comando] # Documentación extendida
# Documentación online# https://www.gnu.org/software/bash/# https://devdocs.io/bash/💡 PRO TIP: Guarda este cheatsheet en tu home:
# Crear archivo con este contenidonano ~/bash_cheatsheet.md# O descargar versión en PDF