Code

Bash Basics on Linux: What is this shell and how to use it – writing your first script

Bash Basics on Linux: What is this shell and how to use it – writing your first script

Practical course: "Linux OS Administration"

Learn more

Using Linux implies a wider range of requests and tasks compared to Windows or macOS users. Bash is a powerful tool that allows you to interact with the system as efficiently as possible. It helps automate routine processes and significantly speeds up task execution, which cannot be achieved using a graphical interface. Mastering Bash will improve your productivity and open up new possibilities for working with Linux.

If you're new to Linux, we recommend checking out our guide to Bash commands. In this article, we'll delve into the nuances of the language and create a script, allowing you to master more advanced aspects of working with Bash.

Content is an important element of any web page, as it helps users and search engines understand the site's content. Well-structured content improves user experience and contributes to higher search engine rankings. To achieve these goals, it's essential to create high-quality, informative text that contains keywords and phrases relevant to the page's topic. It's also important to keep content unique and relevant to attract visitors and keep them on the site. Proper use of headings and subheadings will help organize information and make it more accessible. Don't forget about the importance of regularly updating content to keep your audience interested and keep up with modern search engine requirements.

  • What is Bash
  • Bash Syntax: What It Consists Of
  • Variables
  • Data Types
  • Branching
  • Loops
  • Functions
  • Writing Your First Script
  • Conclusion

What is Bash

Bash (Bourne Again SHell) is the primary command shell used in most Linux distributions and macOS. It is a powerful tool that not only provides users with an interface for executing commands but also serves as a programming language for creating scripts. Bash allows you to automate tasks, manage system processes, and perform complex operations with files and data. Due to its popularity and widespread use, Bash is an important part of the Unix-like operating system ecosystem.

The Bash language offers a wide range of capabilities, including support for variables, arrays, loops, functions, conditional and arithmetic operators, and input/output operations. Bash's primary advantage is its ability to create scripts, which significantly simplify computer tasks and automate routine processes. Bash scripts can be used to automate data backups, manage system resources, process text files, and perform many other operations, making them an indispensable tool for system administrators and developers.

  • Quickly rename all files in a folder;
  • Generate random passwords;
  • Create and send reports via email;
  • Check and update the system and applications;
  • Clear the browser cache with a single command.

In this article, we will focus on writing the last script on our list. Before moving on, it is important to familiarize yourself with advanced Bash syntax, which includes key elements such as variables, operators, loops, and functions. Understanding these constructs will help you effectively create and optimize your scripts.

Frame: the cartoon "Cars" / Pixar

We recommend that you read additional materials:

Bash provides powerful tools for automating and optimizing tasks on your computer. Using the command line, you can significantly speed up processes that would otherwise take a long time to complete manually.

With Bash, you can create scripts that automate everyday tasks, such as file management, data processing, and executing system commands. This not only improves your efficiency but also reduces the likelihood of errors associated with manual entry.

Furthermore, using commands such as `find`, `grep`, and `awk` allows you to quickly process and analyze large amounts of information. For example, `find` lets you quickly find files by specific criteria, while `grep` helps you search for text within files.

For more complex tasks, you can use functions and loops in Bash scripts, allowing you to create more flexible and powerful tools. It's also important to remember the ability to use pipes and redirections, which open up additional possibilities for processing data.

Therefore, learning Bash and using its capabilities will significantly speed up the work you do on your computer, making you more productive and organized.

Bash Basics: Syntax, Variables, and Commands

Coding in the Linux terminal is an essential skill for developers. To open the terminal, use the keyboard shortcut Ctrl + Alt + T. If you're eager to master Bash but don't yet use Linux, you can code in online terminals such as Replit. This will allow you to practice and learn Bash commands in a comfortable environment.

Variables are easy and straightforward to declare in Bash. To create a variable, simply choose a name and assign a value to it. Variable names must begin with a letter or an underscore and can contain letters, numbers, and underscores. Spaces around the equal sign are not allowed. For example, to declare a variable named `MY_VARIABLE` and the value `Hello World`, you would write: `MY_VARIABLE=»Hello World»`. The variable can then be used in a script, for example, to display its value on the screen. The `$MY_VARIABLE` syntax is used for this. Proper use of variables in Bash allows you to create more dynamic and flexible scripts, which greatly simplifies the automation of tasks.

The message variable now contains the text message "Hello, World!" To display this message, we use the echo command. This is a simple and effective way to display the value of a variable on the screen.

It is important to remember the role of spaces in Bash. They act as separators between tokens. If spaces are present in a command, Bash perceives them as separate elements, which can lead to errors when executing scripts or commands. Therefore, you should be careful when using them to avoid problems when working on the command line.

The following code will generate an error:

The $ symbol in Bash is often called the expansion character. Its placement before a variable name signals that the variable's value should be used, rather than a string with the same name. This is an important aspect of working with variables in Bash, allowing you to dynamically retrieve data and make your code more flexible. Understanding the role of the $ symbol is key to effectively writing scripts and automating tasks in the command line environment.

The following code will display the message "message".

To store the value entered by the user in a variable, use the read command. This command allows you to capture user input and assign it to a specified variable. For example, you can use the following construction: read variable_name. After executing this command, the value entered by the user will be stored in the specified variable, allowing you to use it later in your script. Using the read command is an important aspect of working with user input on the command line and scripts.

To add a message before the user enters data, use the -p flag with the read command, and then specify the message text. This makes the input process more informative and user-friendly.

Bash has a number of rules for naming variables. First, a variable name must begin with a letter or an underscore. It can contain letters, numbers, and underscores, but must not include spaces or special characters. Letter case matters, so variables with different cases are considered different. You should avoid using reserved words and built-in language commands. It is also recommended to use clear and descriptive names for variables to make the code easier to read and understand. Proper naming of variables in Bash helps to avoid errors and makes scripts easier to maintain and modify.

  • A variable name must begin with a Latin letter (lower or uppercase) or the underscore _.
  • It can include letters, numbers, and the underscore, but cannot contain spaces or special characters.
  • The case of letters in variable names matters. For example, the variables var1 and Var1 will be treated as different.
  • It is not recommended to use Bash reserved words as variable names.

We have successfully created our first variable. Congratulations! So far, this variable contains only one data type - a string. However, Bash supports many other data types. Let's look at some of them.

An important caveat is that it is necessary to consider all aspects of the subject at hand. This includes not only the actual data, but also the context in which it is presented. When analyzing information, it is important to keep in mind the potential implications and nuances that may affect the final conclusions. Understanding these points will help avoid misunderstandings and ensure a more accurate understanding of the topic.

Bash does not have a strict type system, unlike a number of other programming languages. The data type is determined by the contents of the variable and the context of its use. In this article, the term "data types" is used conditionally for ease of understanding. Please understand this simplification.

Strings are sequences of characters enclosed in quotation marks. In Bash, strings can be formatted with either single ‘…’ or double «…» quotation marks. For example, "Hello" and "World" are examples of strings. Using different types of quotation marks has its own considerations: single quotes preserve the contents as is, while double quotes allow special characters and variables to be interpreted. Proper use of strings in Bash is an important aspect of programming, ensuring the correct execution of scripts and data processing.

Numbers in Bash are integer values ​​that can be used to perform various arithmetic operations. Bash supports basic mathematical operations such as addition, subtraction, multiplication, and division. To perform arithmetic operations in Bash, you must use the dollar sign ($) before the expression and surround it with double parentheses. This allows the expression to be interpreted correctly and produces the expected results. Using arithmetic in Bash is an important aspect of scripting and automating tasks on Unix-like systems.

The expr command is a powerful tool for performing arithmetic operations, string manipulation, and logical calculations on Unix-like systems. With it, users can easily perform mathematical calculations, compare values, and process text strings directly on the command line. expr supports basic arithmetic operations such as addition, subtraction, multiplication, and division, as well as comparison and logical operations. Due to its simplicity and functionality, the expr command is often used in scripts to automate tasks and process data. It allows for efficient manipulation of numeric and string values, making it an indispensable tool for system administrators and developers. Using the expr command can significantly simplify complex calculations and data manipulation in various scenarios.

The standard Bash libraries provide the ability to perform various arithmetic operations. Supported operations include addition, subtraction, multiplication, and division. Using built-in commands and functions, you can effectively process numeric expressions and perform mathematical calculations. Bash allows you to work with both integers and fractional numbers, making it a useful tool for automating tasks involving numerical data. Understanding arithmetic operations in Bash will help you optimize your scripts and increase their functionality.

  • Addition - +.
  • Subtraction - -.
  • Multiplication - *.
  • Integer division - /.
  • Modulo - %.
  • Exponentiation - **.

Arithmetic operators in Bash have limitations when working with floating-point numbers. This means that standard operators such as +, -, *, / cannot correctly handle fractional values. To perform mathematical operations with floating-point numbers in Bash, it is recommended to use specialized tools such as bc or awk, which provide the necessary functionality. This is important to keep in mind when writing scripts to avoid errors and obtain accurate calculation results.

Arrays are a type of variable that allows you to store multiple values ​​at once. Array elements are listed in parentheses, separated by spaces. Arrays provide a convenient way to organize data, allowing you to easily access individual elements and perform operations on groups of values. They are widely used in programming to store lists, collections, and other data structures. Understanding how to work with arrays is fundamental to effective programming and the development of modern applications.

When working with arrays in the programming language, curly braces are used. To print individual elements of an array, you must use the dollar sign ($) in combination with the element index, enclosed in square brackets. This approach allows you to efficiently manipulate data and access the desired information in the array. Proper use of indices and parentheses is key to successfully working with arrays.

If you need to retrieve all the elements of an array, use the * or @ symbol instead of specifying the index in square brackets. This allows you to retrieve the full list of elements, which simplifies working with arrays and makes the code more readable. The use of such symbols is often used in programming languages ​​and can significantly simplify the process of manipulating data.

Boolean values, or Booleans, play a key role in programming because they allow you to test conditions. These values ​​can have two states: true and false. In programming languages, Boolean values ​​are often used in conditional statements such as if and while. When a condition evaluates to true, the specified action is performed, allowing you to create dynamic behavior in your code. Understanding Boolean values ​​and their application is fundamental to effectively working with conditions and loops in programming.

In Bash, Boolean values ​​are represented as integers, where 0 represents true and any other number is interpreted as false. When displaying a Boolean value, 0 is displayed instead of true. This is important to keep in mind when working with conditions and logical operations in Bash scripts, as understanding these principles allows you to more effectively manage program execution logic.Bash provides comparison operators for working with strings. For example, you can use the `=` operator to test for string equality, and the `!=` operator to test for inequality. The `-z` operator tests whether a string is empty, while `-n` is used to test whether a string is not empty. These operators are important tools when writing Bash scripts, as they help you efficiently process text data and perform conditional operations based on string values.

  • = tests whether two strings are the same.
  • != tests whether two strings are different.

These symbols are intended to represent numbers.

  • -eq tests whether two numbers are equal.
  • -ne tests whether two numbers are different.
  • -gt tests whether the first number is greater than the second.
  • -lt tests whether the first number is less than the second.
  • -ge outputs true if the first number is greater than or equal to the second.
  • -le outputs true if the first number is less than or equal to the second.

Comparison operators can be used with the test command. This command takes two values ​​and a comparison operator, returning a result of 1 or 0 depending on whether the condition is met. Using the test command allows you to effectively test various conditions in scripts and automate tasks, making it an essential tool for developers and system administrators.

Comparison operators can be used not only with the test command, but also within square brackets [ ]. To use these operators effectively, it is important to understand the basics of working with branching in scripts.

If-then-else branching provides a way to test conditions in programming. They allow you to execute one set of commands if the condition is true, and an alternative set if the condition is false. The structure looks like this:

Note that the opening and closing square brackets must be separated from their operands by spaces. This rule must be followed to ensure the correctness and readability of the code. Correct use of spaces helps avoid errors in interpreting expressions and improves the visual perception of the code. By following this rule, you will improve the quality of your program code and simplify its maintenance.

If it is necessary to check an additional condition along with the main one, the elif construct is used. This construct allows you to add additional checks to the logical flow of the program, which makes the code cleaner and more understandable. Using elif helps avoid nested conditional statements and improves code readability. This way, you can effectively manage multiple conditions, ensuring the correct execution of the program depending on the specified criteria.

There is a more compact form of writing a conditional construct - if-then. It is used in cases where only one condition needs to be checked.

Commands will be executed only if the condition is true.

We present to your attention a script that checks the correctness of the entered password. This code will help ensure that the user has created a strong password that meets the specified security criteria. Understanding the rules of password validation is important for both developers and users to protect their data. Let's consider how to implement such a check using a script.

In Bash, there are logical operators && (logical AND) and || (logical OR), which allow you to combine multiple conditions and return the corresponding Boolean values. Using these operators helps create more complex logical expressions, making scripts more powerful and flexible. For example, the && operator returns a true value only if both conditions are true, while the || operator returns a true value if at least one of the conditions is true. These constructs are widely used in scripting to control execution flow and handle errors.

An example program with added login checking would look like this. We are integrating an authentication mechanism that ensures user login security. This ensures that only authorized users have access to the system. Login verification occurs based on the entered data, which is compared with records in the database. Upon successful authentication, the user is granted access to the program's functionality, which significantly improves the user experience and protects confidential information.

The value true and the message "Password accepted" will be issued only if both conditions are met.

In Bash, as in most programming languages, loops are used, which are divided into two main types. These loops allow you to perform repetitive operations, making your code more efficient and convenient. The first type is a conditional loop, which continues as long as a specified condition is true. The second type is a fixed-iteration loop, which executes a specified number of times. Using loops in Bash greatly simplifies automation and data processing tasks on the command line.

  • for - when the number of iterations is known in advance.
  • while - when the number of iterations is not known in advance.

The for loop signature is a key element in programming languages ​​that allows you to perform repetitive operations. The basic structure of a for loop includes three main components: initialization, condition, and iteration. Initialization sets the initial value of the counter, the condition determines when the loop should end, and the iteration updates the counter value after each iteration. With the for loop, developers can effectively manage processes that require executing the same code repeatedly, making it an indispensable tool in programming.

The number of iterations between the "in" and "do" keywords can be specified using a simple enumeration of elements. This allows for more efficient control over the code execution process and makes it easier to understand. Using enumerations in this context not only improves readability but also helps to better understand the logic of the program. Properly specifying iterations is an important aspect when writing efficient algorithms, which in turn can improve the performance of your code.

Iterating over the elements of an array is an important task in programming. There are several ways to accomplish this, including using loops such as for and while, and methods such as forEach and map. Each of these approaches has its own advantages and can be used depending on the specific requirements of the task. Iterating over an array allows access to each element, which opens the possibility of performing various operations, such as filtering, transforming, or aggregating data. Effective use of iteration methods can significantly improve the performance and readability of code, which is especially important when working with large amounts of information. The correct choice of array iteration method can optimize program execution and improve its scalability.

Arithmetic expressions are used to precisely specify the required number of iterations. These expressions help determine the number of times certain actions should be performed within an algorithm or program. Using arithmetic expressions to specify iterations improves code readability and increases its efficiency, since the developer can easily change the number of iterations simply by editing the expression. This is especially important in the context of optimizing program performance, where the number of iterations can significantly impact execution time and resource usage.

The signature of a while loop is represented in the following format:

The while loop is used to execute a block of code as long as the specified condition remains true. Its basic structure includes the "while" keyword, followed by a condition in parentheses and a loop body in curly braces. If the condition is true, the code within the loop body will be executed repeatedly. This allows for efficient handling of tasks where the number of iterations is not known in advance, providing flexibility in controlling the flow of program execution.

A condition is an expression whose result can be true or false. In the context of loops, commands will be executed as long as the condition returns a true value. This allows for the creation of efficient and controllable loops that continue execution until certain criteria or conditions are met.

Let's improve the password validation program so that it continues to prompt for input until the user enters the correct password. This will provide stronger security and prevent access to the system in case of incorrect entry. Improving the program's functionality will allow users to successfully pass the validation and also increase the level of security. Using this approach, we will create a more interactive and secure interface for users.

This example demonstrates the use of a while loop to prompt the user for a password. The loop continues to prompt for input until the entered password matches the correct value stored in the variable. The comparison is performed using the operator [«$user_input» != «$password»]. This ensures security until the user enters the correct password. This approach ensures that access to the system will be granted only if the credentials are entered correctly, which is an important aspect of information security.

  • If the password is incorrect, the program displays an appropriate message, and the loop continues.
  • If the password is correct, the program displays a message accepting the password and terminates.

Functions in Bash have the following syntax:

A simple example of a function without arguments looks like this:

A function that takes arguments is an important element of programming. It allows you to pass data to the function for processing. When creating such a function, you need to define the parameters that will be used inside its body. These parameters serve as variables that can receive the values ​​passed when calling the function.

Correct naming of parameters and their types is important because it makes the code easier to understand and maintain. Using arguments in functions helps to create more versatile and reusable code. This avoids duplication, improves readability, and makes the program more structured.

When working with functions that accept arguments, it is also important to consider their number and types. Depending on the program's needs, a function can accept both required and optional arguments. Handling such parameters can significantly improve the functionality of an application and optimize its operation.

Therefore, functions with arguments play a key role in developing effective code, making them indispensable in any programming language.

At this stage, the current state of the content is analyzed. We strive to improve the text, optimize it for search engines, and make it more appealing to readers. This includes adjusting keywords, improving sentence structure, and emphasizing the main topic. The main goal is to create high-quality and informative content that will meet user queries and contribute to better ranking in search engines.

  • Using the local keyword, we created two local variables - that is, variables that exist only within the function.
  • We placed the text in one of them, and the number of repetitions in the second.
  • Then we created a loop that takes the text from the first variable and repeats it as many times as specified in the second.
  • We called the function, passing it the values ​​​​hello and 3 - that is, we ordered the word "hello" to be repeated three times.

Well, hello, Bash! Writing your first script

It's time to put what we've learned into practice. In this tutorial, we'll create a script that will automatically clear the browser cache and DNS. This will help improve system performance and resolve potential website access issues.

Our script will consist of three functions. The first function is designed to clear the browser cache, the second to clear the DNS cache, and the third will present the user with a small menu allowing them to select the desired action. This approach will ensure ease of use and effective caching management, which is especially important for optimizing web applications.

Let's start with a shebang - a special string that specifies which program to use to run the script. Since we plan to use Bash located in the /bin directory, the shebang will look like this:

Let's create a function to clear the browser cache. The comments will provide a syntax breakdown and an explanation of how the code works. This function will help improve the performance of web applications by eliminating issues related to stale data in the cache. Proper cache management is an important aspect of web development, as it allows users to receive up-to-date information and improves the overall experience of the site. Let's look at the function implementation and its syntax.

In this section, we'll look at how to create a function to clear the DNS cache. Clearing the DNS cache can be useful for troubleshooting connection issues and updating domain information. This procedure helps reset temporary records that may be outdated or incorrect. We'll present simple code that will allow you to effectively clear the DNS cache on your device, thereby ensuring stable network connections and access to up-to-date resources.

Now let's move on to the important step. We'll create a simple menu that will allow the user to choose whether to clear the browser cache or the DNS cache. This will help improve performance and eliminate possible page loading issues. Proper cache management is a key aspect of optimizing the web experience.

Our script has successfully completed. To run it, simply call the clear_cache function. This will effectively clear the cache and ensure the smooth operation of your application.

In theory, it is possible to create a script that can be significantly improved. For example, you could add support for multiple browsers, implement administrator rights checking, and implement other useful features. However, for now, this will be quite sufficient.

What's next

You've mastered the basic elements of the Bash language and have already written your first script—congratulations! If you want to improve your skills and solve additional Bash problems, we recommend using the free online trainer. This resource is suitable for beginners and offers accessible and understandable tasks that will help you confidently develop your Bash programming skills.

We recommend checking out the TryBash project, which offers basic theory in the form of short interactive lessons. Here you can get a handy cheat sheet with essential Bash commands, which will save you from constantly searching for information on Google during your training and practice. This resource is great for both beginners and those looking to brush up on their Bash skills.

If you're looking to deepen your knowledge of Bash scripting, we recommend checking out the "Advanced Bash Scripting Guide." This resource is available in English, but a high-quality amateur translation exists. You might also consider taking the Skillbox "Linux OS Administration" course, where you'll find a wealth of useful materials and practical skills.

Learn more about our topic. We offer helpful tips and up-to-date information to help you gain a deeper understanding of the fundamentals. Our goal is to provide you with relevant, high-quality materials to help you in your work. Stay tuned for updates and stay up-to-date with the latest news.

  • Basic Linux Terminal Commands and Keyboard Shortcuts (as well as Unix, macOS, and FreeBSD)
  • Test. Curse like Linus Torvalds
  • The Man Who Created Linux: A Biography of Linus Torvalds

Linux OS Administration

You will get acquainted with the Linux OS and its advantages, learn how to work with the command line and manage network connections. You can become a Linux administrator, configure servers, and maintain their operation.

Find out more