Aprende Bash conmigo - Día 7

Aprende Bash conmigo Día 7: cómo crear y usar funciones en Bash, estilos con function y con paréntesis, ejemplos prácticos y buenas prácticas de scripting.

28 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Aprende Bash conmigo - Día 7: Funciones

Una función en Bash es un bloque de código con nombre que defines una vez y puedes invocar varias veces dentro de tu script o en la sesión del shell. Es como un mini guion dentro de tu guion que ayuda a organizar, reutilizar y simplificar tareas repetitivas.

Cómo declarar una función Nota importante: normalmente conviene declarar la función antes de llamarla, aunque verás una excepción si trabajas con funciones anidadas porque el intérprete analiza el script antes de ejecutar comandos.

Estilo 1 con la palabra clave function Ejemplo: #!/bin/bash function mi_funcion { echo Hola desde funcion } Explicacion: la palabra function indica que vas a definir una funcion; mi_funcion es el nombre que usas luego para invocarla; las llaves { } encierran el cuerpo. La llave de apertura debe estar en la misma linea que el nombre y debe haber un espacio antes de {.

Estilo 2 con parentesis Los parentesis son obligatorios en este estilo Ejemplo: mi_bash() { echo Hola desde funcion } Aqui los parentesis despues del nombre le dicen a Bash que esto es una definicion de funcion. Se requiere un espacio entre () y { y cada comando dentro puede ir en su propia linea o separado por ;.

Reglas de formato: asegura un espacio entre () y { cuando uses parentesis; coloca la } de cierre en su propia linea o separada correctamente; escribe cada comando en su propia linea para mayor claridad.

Ejemplo practico estilo 1: #!/bin/bash # comprobar si existe el archivo que almacena hashes de contrasena function test_shadow { echo ---comprobando archivo shadow--- if [ -e /etc/shadow ]; then echo shadow file exists fi } Llamada a la funcion al final del script: test_shadow

Desglose del ejemplo: la primera linea shebang indica que se ejecutara con /bin/bash; los comentarios empiezan con #; test_shadow es la funcion que imprime un mensaje y luego usa if [ -e /etc/shadow ] para comprobar existencia del archivo; -e significa que existe cualquier tipo de archivo; fi cierra el bloque if.

¿Y lo de declarar antes de llamar que mencionamos anteriormente? Cuando Bash carga un script realiza una fase de analisis donde identifica definiciones de funciones y estructura del guion, y despues ejecuta linea por linea. Esa fase de analisis permite en muchos casos invocar funciones que estan definidas mas abajo si la invocacion ocurre desde otra funcion o depende del orden de ejecucion tras el analisis. Aun asi, por claridad y para evitar sorpresas es buena practica declarar funciones antes de su uso.

Consejo practico: si estas empezando con scripting, ejecuta tus scripts, observa la salida y luego vuelve a leer las explicaciones para consolidar el aprendizaje. Prueba a crear funciones pequeñas, llamarlas desde otras funciones y ver como cambia el flujo.

En Q2BSTUDIO aplicamos buenas practicas de scripting y automatizacion en proyectos de desarrollo de software y aplicaciones a medida para mejorar eficiencia y seguridad. Si necesitas soluciones de software a medida o aplicaciones a medida visita nuestros servicios de desarrollo multiplataforma. Tambien integramos automatizacion de procesos con scripts y orquestacion, conoce nuestras propuestas en automatizacion de procesos.

Ofrecemos servicios completos que incluyen inteligencia artificial, ia para empresas, agentes IA, ciberseguridad y pentesting, servicios cloud AWS y Azure, servicios de inteligencia de negocio y power bi para transformar datos en decisiones. Palabras clave que describen nuestro trabajo: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA y power bi.

Si quieres que te ayudemos a automatizar tareas con Bash, desplegar en la nube o integrar modelos de IA en tus aplicaciones, en Q2BSTUDIO somos especialistas y podemos acompañarte desde el diseno hasta la puesta en produccion.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat