Automatizar Tmux con Bash Script

avatar
(Edited)

Hoy quiero compartir con ustedes un poco de código, ya que estoy creando nuevos script para automatizar algunas tareas que suelo hacer con regularidad. Si, los vagos nos caracterizamos con eso, siempre queremos hacer más con menos. El hecho es que quería automatizar una tarea, que por muy pequeña que parezca, suele ser tediosa.

Desde que estoy activo administrando alguno que otro servidor, y por supuesto, mi propio servidor, Tmux se ha convertido en una herramienta imprescindible dentro de mi flujo de trabajo, permite crear sesiones virtuales del terminal. Ya hable sobre Tmux en otra publicación, así que no entraré en detalles aquí sobre ella, no es la intención de la publiciación.

Actualmente mantengo tres sesiones abiertas de Tmux en mi servidor, una de ellas suele tener hasta 9 paneles internos (nueve ventanas de la terminal dentro de una misma sesión). Cuando necesito reiniciar el servidor o por razones de externas se produce un apagado, requiero crear cada sesión nuevamente, no es complicado pero sí tedioso, y más en esa sesión donde necesito crear los 9 paneles, además que yo poseo cierto grado de proteccionismo, me gusta que queden perfectamente simétricos, tarea que puede resultar difícil.

Para lo expuesto en el párrafo anterior, me puse en la tarea de investigar cómo podría solucionar este "problema" con un script en bash. Elegí bash porque puede ser lo más simple para ejecutar en la terminal, es ligero y no requiere instalación ni creación de un entorno virtual. Encontré la misma inquietud en un foro de superuser, Foro 1 y Foro 2, donde las respuestas me sirvieron de guía para luego solicitar la ayuda de Chat GPT a organizar el script (tengo poco conocimiento en bash), y luego de crear el prompt que tratara de explicar exactamente el problema, la IA me dio un código muy cercano a lo que necesitaba, pero con varios errores que me tocó modificar con algo de ensayo y error, además de aplicar la lógica de programación. Pero ya basta de tanto rodeo y vamos al código.

Script en bash para crear sesión en Tmux y una matriz con paneles 3x3

#!/bin/bash

# Nombre de la sesión
sesion="mi_sesion"

# Crear la sesión
tmux new-session -d -s $sesion

# Crear la matriz 3x3 de paneles
for i in {0..2}; do
    # Divide la ventana verticalmente en la primera columna
    if [ $i -gt 0 ]; then
        tmux split-window -v -t $sesion -c
        tmux select-layout tiled
    fi

    for j in {0..1}; do
        # Calcula el índice del panel
        index=$((i * 2 + j + 1))

        # Divide la ventana horizontalmente
        tmux split-window -h -t $sesion

        # Selecciona el diseño "tiled" después de cada división
        tmux select-layout tiled

        # Renombra el panel con el índice
        tmux select-pane -t $sesion:$index -T "Panel $index"
    done
done

# Vuelve a la primera ventana
tmux select-pane -t $sesion:1

# Adjunta a la sesión
tmux attach-session -t $sesion

Salida:

Como ven el script está comentado y explica el flujo del código. Básicamente el truco esta en el ciclo for y en el comando tmux select -layout tiled, que es el encargado de dar la simetría a los paneles. Este script genera una matrix 3x3, pero si desea cambiar el número de paneles puedes jugar con el rango de valores que hay dentro del ciclo for.

Por ejemplo, para una matriz 2x2 editamos sólo rangos de los ciclos for de la siguiente manera: for i in {0..1}; do y for j in {0..0}; do. Con esto sería suficiente para cambiar el rango de la matriz y tú podrías jugar con ello para crear otras formas.

Esto es todo por hoy. Espero que esta publicación haya sido de utilidad. Cualquier comentario, sugerencia o aporte es bienvenido. Un abrazo a todos.


English version, translated with Google Translate

Today I want to share with you some code, since I am creating new scripts to automate some tasks that I usually do regularly. Yes, we lazy people are characterized by that, we always want to do more with less. The fact is that I wanted to automate a task, which, no matter how small it may seem, is usually tedious.

Since I am active managing some servers, and of course, my own server, Tmux has become an essential tool in my workflow, allowing me to create virtual terminal sessions. I already talked about Tmux in another post, so I won't go into details about it here, it is not the intention of the post.

I currently have three open Tmux sessions on my server, one of which usually has up to 9 internal panels (nine terminal windows within a single session). When I need to restart the server or for external reasons a shutdown occurs, I need to create each session again, it is not complicated but tedious, and more so in that session where I need to create the 9 panels, in addition to the fact that I have a certain degree of protectionism, I I like them to be perfectly symmetrical, a task that can be difficult.

For what was stated in the previous paragraph, I set myself the task of investigating how I could solve this "problem" with a bash script. I chose bash because it may be the simplest to run in the terminal, it is lightweight and does not require installation or creating a virtual environment. I found the same concern on a superuser forum, Forum 1 and Forum 2, where the answers served as a guide for me to later request the help of Chat GPT to organize the script (I have little knowledge of bash), and after creating the prompt that tried to explain exactly the problem, the AI gave me a code very close to what I needed, but with several errors that I had to modify with some experimentation and error, in addition to applying programming logic. But enough of this detour and let's get to the code.

Bash script to create a session in Tmux and a matrix with 3x3 panels

#!/bin/bash


# Session name
session="my_session"


# Create the session
tmux new-session -d -s $session


# Create the 3x3 matrix of panels
for i in {0..2}; do
     # Split the window vertically in the first column
     if [ $i -gt 0 ]; then
         tmux split-window -v -t $session -c
         tmux select-layout tiled
     fi


     for j in {0..1}; do
         # Calculate the panel index
         index=$((i * 2 + j + 1))


         # Split the window horizontally
         tmux split-window -h -t $session


         # Select the "tiled" layout after each split
         tmux select-layout tiled


         # Rename the panel with the index
         tmux select-pane -t $session:$index -T "Panel $index"
     donated
donated


# Return to the first window
tmux select-pane -t $session:1


# Attached to session
tmux attach-session -t $session


Exit:

As you can see, the script is commented and explains the flow of the code. Basically the trick is in the for loop and in the command tmux select -layout tiled, which is responsible for giving symmetry to the panels. This script generates a 3x3 matrix, but if you want to change the number of panels you can play with the range of values inside the for loop.

For example, for a 2x2 matrix we edit only ranges of the for loops as follows: for i in {0..1}; do and for j in {0..0}; do. This would be enough to change the range of the matrix and you could play with it to create other shapes.

That is all for today. I hope this post has been helpful. Any comment, suggestion or contribution is welcome. A hug to all.


Mi intención con esta publicación es dar mi aporte al software libre y al código abierto, difundiendo al público en general todos los beneficios, ventajas y facilidades de obtener versiones seguras, optimas y de vanguardia.


Las imágenes son mías o capturas de pantalla tomadas por mí, a menos que se indiquen fuentes externas.


Discord: alberto0607

Sígueme en X: alberto_0607

Posted Using InLeo Alpha



0
0
0.000
10 comments
avatar

Yay! 🤗
Your content has been boosted with Ecency Points, by @alberto0607.
Use Ecency daily to boost your growth on platform!

0
0
0.000
avatar

Muchas gracias por compartir esta herramienta, desde ya te digo que voy a estudiarla para ponerla en uso. Esto me recuerda que en cierto momento tuve que hacer mi propios scripts para monitorear el servidor.

Por otro lado, muchas veces las personas les tienen temor a la consola, sin embargo es la vía mas fácil para aprender y entender de verdad el potencial que tiene Linux.

0
0
0.000
avatar

!ALIVE

0
0
0.000
avatar

@cumanadigital! You Are Alive so I just staked 0.1 $ALIVE to your account on behalf of @ visual.alive. (2/20)

The tip has been paid for by the We Are Alive Tribe through the earnings on @alive.chat, feel free to swing by our daily chat any time you want, plus you can win Hive Power (2x 50 HP) and Alive Power (2x 500 AP) delegations (4 weeks), and Ecency Points (4x 50 EP), in our chat every day.

0
0
0.000
avatar

Aunque para un usuario común no es necesario la terminal, pero si desea aprender esa es la vía. El miedo es normal, puedes romper el sistema. Gracias por comentar.

0
0
0.000