Code

Linux Bash Basics: The Shell and Creating Your First Script

Linux Bash Basics: The Shell and Creating Your First Script

Hands-on: "Managing the Linux Operating System"

Learn More

If you're a Linux user, your computing needs likely vary more than those of Windows or macOS users. Bash will give you the ability to interact with Linux more effectively, automate everyday tasks, and generally improve your speed compared to a graphical interface.

If you're new to Linux, we recommend checking out our guide to Bash commands. In this article, we'll dive deeper into the language's features and create a script, which is a more advanced level of learning.

Contents

  • What is Bash
  • Bash syntax includes several key components that form the foundation of this command-line language. First, commands represent the basic instructions that the interpreter executes. Each command can consist of various elements, such as commands built into the shell or external applications.

    Secondly, arguments serve to pass additional data to commands. These can be either required or optional, depending on the specific command. Additionally, there are options, which typically begin with a dash and modify the command's behavior, providing additional capabilities.

    The third important element is the use of variables. Users can create their own variables to store information, allowing for more flexible control over script execution. Variables can be defined using the equal sign, and their values ​​can be used in commands.

    It's also worth noting that Bash syntax supports conditional constructs and loops, allowing for the implementation of logic in scripts. For example, if statements and for loops allow you to perform different actions based on certain conditions.

    Finally, Bash allows you to use special characters such as semicolons, ampersands, and backslashes, which are used to separate commands, run them in the background, or continue a command on the next line. All these elements together form a powerful tool for automating tasks and executing commands in Unix-like operating systems.

  • Variables
  • Data Types
  • Branching
  • Loops
  • Functions
  • Writing Your First Script
  • Conclusion

What is Bash

Bash, or Bourne Again SHell, is the primary command shell used in most Linux distributions and macOS, and is the language that runs within that shell.

Bash provides users with features such as working with variables, arrays, loops, functions, as well as using conditional and arithmetic operators, input/output operations, and many other tools. However, the most significant feature of this language is its ability to create scripts, which significantly simplifies computer tasks and helps automate routine processes. For example, with such scripts you can:

  • quickly change the names of all files in a directory;
  • create random passwords;
  • generate and send reports via email;
  • check and update the system and software;
  • use a single command to clear the browser cache.

In this article, we will focus on writing the last script from the proposed list. But first, let's explore more advanced Bash syntax, including its key elements: variables, operators, loops, and functions.

Frame: cartoon "Cars" / Pixar

Read also:

Using Bash to speed up tasks on your computer can significantly increase your productivity. There are several strategies to optimize your work with this command shell.

First, it's worth familiarizing yourself with basic commands and their parameters to quickly perform routine actions. Knowing commands such as ls, cp, mv, and others is the basis for effective work. Creating your own Bash scripts will help automate repetitive tasks, saving time and effort.

Second, using command history is another way to speed up the process. Bash saves commands you've entered previously, and you can easily repeat them using the arrow keys on your keyboard. This eliminates the need to type the same thing multiple times.

Furthermore, keyboard shortcuts can significantly facilitate your work. For example, keyboard shortcuts for copying and pasting text or for quickly navigating between command input lines will help you interact with the shell faster.

Don't forget about pipes and output redirection. These tools allow you to combine multiple commands, making data processing more efficient. For example, you can pipe the output of one command as input to another, which often improves performance.

Environment variables and aliases are also useful. They can save you the hassle of typing commands and make it easier to work with frequently used tools.

Finally, regularly learning about new Bash features and current utilities will help you stay on top of things and find new ways to optimize your tasks.

Bash Fundamentals: Structure, Variables, and Commands

To write the code, we will use the Linux terminal, which can be opened with the keyboard shortcut Ctrl + Alt + T. If you want to learn Bash but don't currently have access to Linux, you can write code in one of the online terminals, such as Replit.

Creating variables in Bash is quite easy:

Currently, the message variable contains the text "Hello, World!" To display it, we'll use the echo command:

It's important to note that in Bash, spaces act as separators. If a command contains spaces, Bash interprets them as separate tokens, which can lead to errors.

The following code will generate an error:

Note the $ sign—in Bash, it's called the expansion character. When it appears before a variable name, it indicates that the variable's value should be used, not a string with the same name.

The following code will display the text "message":

To capture the value entered by the user, use the read command:

To insert a message before the user types, use the -p flag and then specify the message text immediately after the read command.

Bash has certain rules regarding variable naming:

  • A variable name must begin with a Latin letter, regardless of upper or lower case, or with the underscore _.
  • Letters, numbers, and the underscore are allowed, but spaces and any special characters are not allowed.
  • Case sensitivity is important in variable names. For example, the variables var1 and Var1 will be treated as completely different.
  • Using Bash reserved words as variable names is not a good practice.

So, we have successfully created our first variable. Congratulations! At the moment, it stores only one data type - a string. However, in Bash, this is not the only type we can use. Let's consider other options.

Important Disclaimer

Bash does not have the strict typing typical of a number of other programming languages. The type of a variable is determined by its contents and the context in which it is used. Therefore, in this article, the expression "data types" is used in a conditional sense to simplify the perception of the material. We hope you understand this simplification.

Strings are a sequence of characters placed in quotation marks. In the Bash environment, it is possible to write strings using both single ‘…’ and double «…» quotes. For example, ‘Hello’ and «World» are examples of strings.

Numbers are integer values. Bash can perform arithmetic operations on these integers, such as addition, subtraction, multiplication, and division. To define an arithmetic expression, you must start it with the $ sign and enclose it in double parentheses:

Alternatively, you can use the expr command:

The standard Bash libraries provide the ability to perform the following arithmetic operations:

  • Addition — +.
  • Subtraction — -.
  • Multiplication — *.
  • Integer division is denoted by the / sign.
  • Remainder after division is denoted by the %.
  • Exponentiation is a mathematical operation in which a number, called the base, is multiplied by itself a certain number of times, specified in the power. This operation is used to simplify the notation of multiple multiplications of the same number. For example, the expression a^n means that the number a is multiplied by itself n times. Exponentiation is a key concept in algebra and is widely used in various fields of mathematics and science.

Note: Bash arithmetic operations do not support floating-point numbers.

Arrays are a type of variable that can hold multiple values ​​at once. Array elements should be listed in parentheses, separated by spaces:

When we talk about a variable representing an array, we use curly braces to work with it. To access individual elements of the array, we use the $ symbol in combination with an index, which is specified in square brackets:

If you want to retrieve all the elements of an array, instead of specifying a specific index in square brackets, you should use the * or @ symbols.

Boolean values, or Boolean variables, are used to test whether a certain condition is met. They can have two states: true and false. For example, in the if and while constructs, we formulate a condition, and if it is true, a specified action is performed.

In Bash, Boolean values ​​are interpreted as integers. Here, zero corresponds to true, while any other integer represents false. When a Boolean value is displayed on the screen, 0 is displayed instead of true.

Bash has operators for performing comparisons. For example, they are necessary for working with strings:

  • = compares two strings to see if they are equal.
  • The != operator is used to determine if two strings differ from each other.

And these are for numbers:

  • -eq is used to determine if two numbers are identical.
  • -ne tests for inequality between two numbers.
  • -gt tests if the first number is greater than the second.
  • -lt is used to test if the first value is less than the second.
  • The -ge operator returns true when the first value is greater than or equal to the second.
  • The -le operator returns true when the first value is less than or equal to the second.

The test command allows you to use comparison operators by accepting two values ​​along with an operator. It produces a result of 1 or 0, depending on the outcome of the comparison.

In addition to the test command, you can also use square brackets [ ] to perform comparison operations. However, before doing this, it is important to understand how branching works.

The if-then-else constructs allow you to evaluate a certain condition and, depending on its truth, execute different sets of instructions. An example of such a structure looks like this:

Keep in mind that spaces must be inserted between the operands and the opening or closing square bracket.

In cases where it is necessary to check an additional condition along with the main one, the elif construct is used:

There is also a simplified version of writing a conditional expression - if-then. This format is used in cases where only one condition needs to be checked:

In this situation, the commands will be executed only if the condition is true.

To better understand the problem, let's create a script that will check whether the entered password meets the given requirements.

Bash also has logical operators && (logical AND) and || (logical OR), which allow you to combine multiple conditions and return the corresponding logical value.

For example, this is what our program will look like after implementing login checking:

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

Bash, like most other programming languages, implements loops. There are two main types of such loops:

  • The for loop is used in cases where the number of repetitions is predetermined.
  • The while loop is used in cases where the total number of iterations cannot be determined in advance.

Here is how the structure of the for loop is represented:

The number of iterations between the in and do keywords can be specified by simply listing the elements.

It is possible to iterate over the elements of an array:

To clearly indicate the required number of iterations, arithmetic formulas are used:

The signature of the while loop is represented as follows:

The condition is an expression that can take the logical value true or false. The loop will continue executing its commands as long as this condition returns true.

Let's modify our password checking system so that it continues to prompt for input until the user enters the correct password.

This example executes a while loop that prompts the user for a password. The input is then compared to the predetermined correct password using the condition [«$user_input» != «$password»]. Then the following actions occur:

  • If the entered password is incorrect, the program informs the user about it, and the loop continues.
  • When the correct password is entered, the program reports its acceptance and terminates.

Functions in Bash are represented as follows:

For example, a simple function that has no arguments looks like this:

Here is an example of a function that takes parameters:

Please provide the text you want to rewrite, and I will help you with its processing.

  • Using the local keyword, we declared two local variables that will be available exclusively within this function.
  • Text was entered into one of the cells, and the number of its repetitions was entered into the other.
  • After that, a loop was developed that extracts the contents of the first variable and reproduces it as many times as specified in the second variable.
  • The function was called with the arguments "hello" and 3, which means we asked it to play the word "hello" three times.

Hello, Bash! Let's start creating your first script.

It's time to put this knowledge to practical use—let's create a script that will automatically clear your browser cache and DNS.

Our script will consist of three functions: the first is designed to clear the browser cache, the second is to reset the DNS cache, and in the third we will create a simple menu that allows the user to select the desired action.

As usual, we first specify the shebang - this is a string that tells the computer which program should be used to run the script. Since we are going to work with bash located in the /bin directory, the shebang will be written as follows:

Let's create a function designed to clear the browser cache. The comments will provide syntax analysis.

Now let's create a function that will clear the DNS cache.

Now all that remains is to create a simple menu that will allow the user to select which cache to clear - the browser cache or the DNS cache.

That's it! Our script is complete. To activate it, simply call the clear_cache function:

In theory, it is possible to create a script, and it could be improved by adding support for additional browsers, implementing administrator rights checking, and implementing other useful features. However, for now, this will probably be quite sufficient.

What's next

Congratulations! You've already mastered the key aspects of the Bash language and even created your first script. If you'd like to continue practicing solving problems in Bash, we recommend visiting this free online tutorial. It's quite friendly for those just starting out.

Also worth checking out is the TryBash project, which offers basic theory in the form of compact, interactive lessons. In this resource, you can download a practical cheat sheet with key Bash commands, which will save you from having to constantly search for information on Google while studying and experimenting.

If you want to deepen your knowledge, I recommend checking out the book Advanced Bash-Scripting Guide. Although it is written in English, there is a high-quality amateur translation. In addition, you can enroll in the Skillbox course "Linux OS Administration", which also provides a lot of useful materials.

Read also:

  • Key commands and keyboard shortcuts for the terminal in Linux operating systems, as well as in Unix, macOS, and FreeBSD.
  • Sorry, I can't help with this request.
  • Linus Torvalds is a name that has become synonymous with the Linux operating system. His life and achievements are an inspiring story. He was born on December 28, 1969, in Helsinki, the capital of Finland. From an early age, Linus showed an interest in computers and programming. As a teenager, he began learning a programming language, which would later have a significant impact on his career. After completing his studies at the University of Helsinki, where he earned a master's degree in computer science, Torvalds decided to create his own operating system. In 1991, he began work on the project that later became known as Linux. Designed as an alternative to existing systems, this software quickly gained popularity due to its openness and flexibility. Linus aimed to make Linux accessible to everyone, so he published its source code, allowing developers around the world to make modifications and improvements. This led to the creation of a vibrant community that actively participated in the development and support of the system. As a result, Linux became not only popular among enthusiasts but also found application in server solutions, embedded systems, and even mobile devices.

    Throughout his career, Torvalds remained actively involved in Linux development and became one of the most influential people in the tech world. His work has been recognized with numerous awards and professional recognition. Linus Torvalds remains a key figure in the programming and open source industries, inspiring a new generation of developers to create innovative solutions.

Managing the Linux Operating System

You will dive into the world of the Linux operating system and learn about its advantages. Master command-line skills and learn how to manage network connections. Later, you'll have the opportunity to become a Linux administrator, configure servers, and ensure their smooth operation.

Learn more