O que são scripts Bash e por que você deveria usá-los?

What are Bash scripts and why should you use them?

A type of programming that your business should not ignore, which is also simple, effective and flexible.

Imagem em destaque

If you mention bash scripts to any technology administrator or developer, you will be greeted with nods of approval or a rousing “Been there, done that.” The reason for this is that bash scripts are an incredibly useful tool that helps make the Linux operating system flexible, powerful, and useful.

But what are bash scripts and why should you use them?

These questions are frequently asked and easily answered. But before listening to the explanation, you should probably first know what bash is. After all, you probably already know what a script is, so putting these two and two together starts in the terminal itself.

What is Bash?

An illustration of the Bash scripting language.

Simply put, bash is a shell and command language used in Linux. Okay, that's great, but what is a shell? In the Linux domain, the shell is a command-line interpreter that provides a user interface for executing commands. Without the shell, you couldn't execute commands. Without commands, there would be no operating system. Without an operating system, there would be no PC.

Therefore, bash is a type of shell that allows you to execute commands in Linux.

But what does this have to do with your development team?

Two words: shell scripts.

What are shell scripts?

An illustration of a Linux shell interface.

Now we come to the heart of the matter. A shell script is a computer program designed to run inside the shell (in this case, bash). Each shell has its own scripting language, and since bash is the default Linux shell, most development and administration teams use the bash scripting language.

With these scripts you can do almost anything. And like Python, they are quite easy to learn and don't require a compiler to use.

To really understand shell scripting, you first need to understand how to use the command line in Linux. Let's take a look at a very simple example. Let's say you want to print the following sentence:

The date and time are

Following the above, you want to print the actual date and time, using the date command. This would be done with:

 echo "The date and time is " $(date)

Press Enter and the output will be something like this:

 The date and time is Wed Jan 19 09:04:16 AM EST 2022

We will now see how this is done with a bash script.

How to create a Bash script

The first thing you should know is that every bash script starts with:

 #!/bin/bash

Create a new file with the command:

 nano date.sh

Add #!/bin/bash to the top of the script, which instructs the terminal that everything found in the file is part of a script. After that, we can create our program with just a few lines. The first thing we will do is format the date however we want using a variable like this:

 formatted_date=$(date +%m_%d_%y-%H.%M.%S)

The above text will display the date in date format (month, day, year) and then the time (hour, minutes, seconds). We will use this variable ( data_formatada ) in conjunction with our echo command on the line:

 echo "The date and time is " $formatted_date

Save and close the file and give the script executable permissions with:

 chmod u+x date.sh

If you run the ./data.sh command the output will be similar to when you ran the echo command from the terminal window.

And that's how you build a bash script.

Why do you need Bash scripts

Now that you understand the basics of how bash scripts work, it's important to know that bash scripts can be anything from simple one- or two-line applications to incredibly complex applications that can do just about anything (from backing up directories in external drives, to run ping tests for site uptime, monitor server performance, and custom administrative tasks. In fact, there's very little that bash scripts can't do (as long as you don't need a GUI).

A huge benefit of using bash scripts is that they can be created with very little (or zero) programming knowledge. This means you can create GUI-less Linux applications without first learning to program.

If you can run a command, you can write a script.

And given the flexibility of bash scripts, you can really get a lot of use out of them before you hit a wall and have to resort to more traditional programming skills.

Pros and Cons of Bash Scripts

An illustration of the pros and cons of Bash scripts.

There are several advantages to using bash scripts and only a few disadvantages.

Advantages of Bash Scripts

Advantages of bash scripts include:

  • Simple to create
  • Can execute multiple commands easily
  • Interactive debugging
  • Portable
  • Time saving
  • Cost benefit
  • Can be automated
  • Installed on almost all Linux operating systems

Disadvantages of Bash Scripts

Bash scripting has its drawbacks, which include:

  • Not as fast as a standard program
  • Limited usability (when compared to traditional programs)
  • Starts a new process for each shell command executed (which means it can be resource intensive if a script is complex)

Conclusion

The longer your administrators work with the Linux operating system, they will eventually resort to shell scripting. In fact, you should encourage them to start with shell scripts to accomplish smaller tasks and then move to traditional development when they hit the inevitable roadblock.

Because shell scripts are so easy to learn and create, they are also a good introduction to programming. If you have interns or first-year developers on staff, ask them to start working with shell scripts as a way to ease the heavier work they'll be doing with Java, JavaScript, or .NET.

Common questions

Can Bash scripts be used on all operating systems?

Bash scripts are natively supported on Unix-based systems such as Linux and macOS. For Windows, Bash can be used through subsystems like the Windows Subsystem for Linux (WSL) or through third-party applications like Cygwin.

Are Bash scripts suitable for large-scale software development?

Bash scripts are generally best suited for small to medium automation tasks, systems administration, and simple control of other software. For large-scale software development, more comprehensive programming languages ​​are typically recommended.

How do Bash scripts compare to Python scripts in terms of ease of use and functionality?

Bash scripts are excellent for file manipulation, system administration, and task automation directly on Unix-like systems. Python, being a complete programming language, is more versatile and easier for complex tasks, data manipulation, and cross-platform applications.

Is programming experience necessary to start writing Bash scripts?

You don't need to have previous programming experience to start writing Bash scripts. Basic Bash scripting can be quite simple and is often a good starting point for learning programming concepts, especially for those who frequently use Unix-like operating systems.

Source: BairesDev

Conteúdo Relacionado

O Rails 8 sempre foi um divisor de águas...
A GenAI está transformando a força de trabalho com...
Entenda o papel fundamental dos testes unitários na validação...
Aprenda como os testes de carga garantem que seu...
Aprofunde-se nas funções complementares dos testes positivos e negativos...
Vídeos deep fake ao vivo cada vez mais sofisticados...
Entenda a metodologia por trás dos testes de estresse...
Descubra a imprevisibilidade dos testes ad hoc e seu...
A nomeação de Nacho De Marco para o Fast...
Aprenda como os processos baseados em IA aprimoram o...
Como engenheiro de software, estou constantemente enfrentando desafios interessantes...
De todas as principais preocupações com segurança, nós suamos...
Eu uso Linux há quase 30 anos e já...
Durante décadas, o Ubuntu foi considerada uma das distribuições...
A web está em constante evolução, e com ela,...
A Inteligência Artificial (IA) tem sido um tema cada...
Você já se sentiu frustrado com a complexidade de...
O OpenStack é uma plataforma de computação em nuvem...
Você já se sentiu frustrado com a criação de...
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.