If the question is: “how to add a program to startup?” - novice users find the answer quickly enough, then the question of running the script during shutdown/reboot confuses them. The article will describe standard way For automatic execution commands when turning linux on and off, as well as an easier way for users who have gdm installed and GUI, for example ubuntu.

Console option.

A little theory.
You should know that there are 7 runlevels in Linux. However, only 6 can be used.
Like all self-respecting programs, the countdown starts from 0.
0 - Stop or turn off the system.
1 - Single-user mode.
2 - Multi-user mode, but without network support.
3 - The same thing, but with the network.
4 — Added for beauty Not used.
5 — Graphics mode with loading the X server.
6 - Reboot.
If you go to the /etc folder (in some distributions /etc/rc.d) you can see folders with 7 run levels.

For example, when you turn off the computer, all scripts from the rc0.d folder will be executed


Here we should dwell in more detail. The fact is that the scripts themselves (or rather scripts) are not in this folder, but there are only links to files that are in the /etc/init.d folder. These scripts perform different tasks depending on the start or stop parameter (for example /etc/init.d/reboot start and /etc/init.d/reboot stop are different commands, but /etc/init.d/reboot will not work at all work). If the first letter in the link is S, then the start parameter is given to the script, and if the letter K (from the word kill) is given, then the stop parameter is given. The number after the letter indicates the order in which the script is executed.
For example, in the above inserted screenshot, the command /etc/init.d/hddtemp stop will be executed first, and then /etc/init.d/networking start.
Enough theory. Let's move on to practice.
In order to add a command to startup, just place it in the /etc/rc.local file.

This part of the article will use nano as the editor, but you can use your favorite editor, such as gedit.

sudo nano /etc/rc.local

And we place our commands just above the line with exit 0.
In order for the commands to be executed before shutting down or rebooting, we need to create a script in the /etc/init.d folder

sudo nano /etc/init.d/scriptname

Paste the following code:

#! /bin/sh
case "$1" in
start)
echo "start signal given"
;;
stop)
echo "stop signal given"
;; esac

If only one signal will be given, then simply comment out the line by placing a # sign at the beginning of the command
For example

...
case "$1" in
start)
#
;;
...

Now we make the file executable:

sudo chmod +x /etc/init.d/scriptname

sudo update-rc.d script_name start 20 0 6 . stop 1 0 6 .

The points are important (both). While exploring the Internet, I got the impression that the syntax of this program sometimes changes. Current examples can be viewed using the command “man update-rc.d”. Examples will be at the bottom.

This command will create 2 links in the /etc/rc directories 0 .d (second number in the command) and /etc/rc 6 .d (third number in the command). Moreover, the script with the stop parameter will be executed first (since it costs 1), and only then with the start parameter (since it costs 20).
If the second parameter is not needed, then you can run the command:

sudo update-rc.d script_name stop 1 0 6 .

I advise you to set the priority higher (i.e. the number after start or stop should be small), preferably less than 20. Otherwise, sometimes my computer would freeze when I tried to reboot.

For ubuntu users, and many other modern distributions with gdm can be used...

Graphic option.

As for autoloading, you can use the method described.
Or simply open “automatically launched applications” with the command:

gnome-session-properties

To execute the script when the computer is turned off, place it in the file /etc/gdm/PostSession/Default

sudo gedit /etc/gdm/PostSession/Default

Right above the exit 0 line.

Create an empty file.

The first line we write:

#!/bin/sh

This line specifies which command shell to use. Next are your teams.

Let's save it under the original name (so as not to coincide with existing ones) in the /usr/sbin/ directory.

In order for the script to run at boot, you need to register it in the /etc/rc.local file up to the line exit 0. If you do not have this file, create it and paste the following content into it:

#!/bin/sh -e #Here we insert a line indicating your script. /usr/sbin/mescripts exit 0

A little more complicated way

Allows you to set the loading sequence and behavior of the script at different runlevels.

We study /etc/init.d/skeleton, based on it we create a script /etc/init.d/my_script that will start/stop our application.

These directories contain scripts for stopping services:

/etc/rc0.d/ /etc/rc1.d/ /etc/rc6.d/

These are service launch scripts:

/etc/rc2.d/ /etc/rc3.d/ /etc/rc4.d/ /etc/rc5.d/

We study them for consistency (the smaller the first digit at the beginning of the script, the earlier the application starts/stops). This can be critical if your application depends on some services.

After we have decided on the launch script and sequence, we perform the following:

Sudo update-rc.d my_script start 70 2 3 4 5 . stop 20 0 1 6 .

Here I determined that my script should start later than the others (70), and stop earlier (20). The numbers 2 3 4 5 0 1 6 indicate load levels.

If you don’t like something, you can delete everything

Sudo update-rc.d -f my_script remove

See man update-rc.d for details.

Executing a script when the network is turned on/off

There is a directory /etc/network/ with subdirectories if-down.d , if-pre-up.d , if-post-down.d , if-up.d . If you place the script in one of these subdirectories, it will be executed respectively when turning off, before turning on, after turning off or when turning on the network.

Another way is to specify one of the following directives in the /etc/network/interfaces file: up , pre-up , post-up , down , pre-down , post-down . For example, the line

Post-up /path/to/script.sh

after turning on the network will execute the script script.sh. You can read more in man interfaces.

In any case, the script must have execution rights set, otherwise it will not be able to run.

First of all, let's figure out what it is script and why it is needed.

Script translated from English - scenario. We all watch films, many of us watch plays. To create a film/play, screenwriters write scripts for them, on the basis of which the actors perform their roles on stage, scene by scene, from which the film/play is made up. The work of creating a script is quite painstaking, where you need to take into account everything down to the smallest detail, so that in the end the artists can fulfill what the screenwriter intended, and the viewer can see a complete work.

Similarly, scripts are written to execute a list of tasks that the user puts together (code) to make them easier and faster to complete in operating system. For writing simple scripts It is not at all necessary to have a programmer education.

First, let's create the simplest one script-Shell to update the system.

I will carry out all actions with the system Ubuntu, but they are also applicable to other systems Linux, derived from Ubuntu. For this we need: Text editor to fill it with the necessary tasks to create a script (code) and Terminal- to execute the created script. These tools are installed in any distribution Linux default.

So, open a text editor Gedit and enter into it the first required characters called shebang.
shebang in programming, this is a sequence of two characters: a hash and an exclamation mark ( #! ) at the beginning of the script file. And add to these characters without spaces /bin/sh- the interpreter where the script will be executed. /bin/sh- this is usually Bourne shell or compatible interpreter command line, which transmits "path/to/script" as the first parameter.
The first required line of the script will look like this:

# My first Ubuntu update Script

The hash sign (#) at the very beginning of the line makes it clear to the interpreter/terminal that this line does not need to be read and executed. The line is needed in the code of this script so that the creator of the script knows what he is going to do in this segment/scene in the code, so as not to get confused in the future when there are many such lines. Such lines with a hash sign are called - commented out .

sudo apt update
sudo apt upgrade -y

-y at the end of the second command makes it clear to the interpreter/terminal that this action/command must be performed automatically, without additional confirmation by the user by pressing a key Enter. y- short for English yes, i.e. Yes.

That's all. Your first script has been created. You should get something like the picture:


All that remains is to save the created file/script and give it Name with a mandatory extension at the end - .sh. Extension .sh assigned to the executable file.
I gave him Name - update.sh, saving in Home folder user:


In order for the created file/script to be executable, it must be given permission to do so. There are two ways to do this.

1. Run the following command in the terminal:

sudo chmod +x update.sh

2. Or open the file manager in Home folder(where you saved the created script), right click on the file, in context menu - Properties - Rights and activate the item - Performance: Allow file to be executed as a program:


To execute the created script, you need to open the terminal (as I wrote at the very beginning of the article that the terminal is a necessary attribute/tool ​​for executing the script), enter sh, separated by a space the name of the script - update.sh and press the key Enter:


Or in the terminal we enter sh and drag from file manager the created file with the script (also separated by a space):


Once the file path is displayed after the command sh and space, just press the key Enter(Enter) to perform a system update:


Now at any time you can update the system using your own script.

Yes, someone might argue that updating the system is not difficult to do by executing these two commands in the terminal, why puff up and create some scripts? That's right. But this is an example of creating a simple script to show that “it’s not the gods who burn the pots” 😃.

Having learned to write and use simple scripts, you can create a script for setting up the system, so that if the system is reinstalled, you can use the created script without having to search the Internet for sites with similar settings every time.

Many of you most likely use system setup sites, such as those that I publish after the next release. Ubuntu - Ubuntu after installation or similar sites. Open one of these sites: http://compizomania.blogspot.com/2016/04/ubuntu-1604.html, then a text editor to create a script.
For example, I made the following blank.

IN text editor enter the first required line:

# Setting up Ubuntu after installation
# System update

The following are the system update commands:

sudo apt update
sudo apt upgrade -y

Description line: Adding repositories:

# Adding repositories

And add the necessary repositories for further installation software:

sudo add-apt-repository "deb http://archive.canonical.com/ $(lsb_release -sc) partner" -y
sudo add-apt-repository ppa:atareao/telegram -y
sudo add-apt-repository ppa:atareao/atareao -y

sudo add-apt-repository ppa:nemh/systemback -y
sudo add-apt-repository ppa:gerardpuig/ppa -y
sudo add-apt-repository ppa:haecker-felix/gradio-daily -y

After the necessary repositories have been added (I repeat, you may have your own repositories, I have an example), you need to update the system:

Description line:

# System update after connecting repositories

And the command to execute:

sudo apt update

Now that the repositories have been added and the system has been updated, it’s time to install programs:

# Installing programs

To install programs, just enter the command once sudo apt install and then through a space in this line add as many programs as you like, the main thing is that they are compiled correctly. If a program consists of several words, its command must be monolithic, i.e. all words in it must be entered through a dash, for example: unity-tweak-tool:

sudo apt install my-weather-indicator telegram skype lm-sensors hddtemp psensor gdebi systemback unity-tweak-tool ubuntu-cleaner gradio -y

Installing additional codecs

# Multimedia and codecs

sudo apt install ubuntu-restricted-extras -y

Disabling system failures

# Disable system crash reporting

sudo sed -i "s/enabled=1/enabled=0/g" "/etc/default/apport"

Well, that's probably all. This generated script file should look like this:


You need to save it (click the button Save) and give Name with extension .sh. I called him Settings\Ubuntu.sh(you can name it differently, but be sure to use the .sh extension):


Let's make the created script executable:

sudo chmod +x Setup\Ubuntu.sh

To execute the created script, enter in the terminal sh and the name of the created script separated by a space, or sh, spacebar and drag the created file into the terminal, as explained earlier in the simplest script and press the key Enter, to carry it out.

Note. Backslash in command Settings\Ubuntu.sh escapes a space in a terminal file name between two separate words.

After the script is executed, store it for future use for possible system reinstallation and re-tuning, best on a separate partition of the hard drive in a folder /home. If there is none, then cloud service (Cloud storage data) type: DropBox, Cloud Mail.Ru, Mega.co etc., so that you can use the script yourself at any time, or help friends or relatives set up the system.

Today we'll talk about bash scripts. These are command line scripts written for bash shell. There are other shells, for example - zsh, tcsh, ksh, but we will focus on bash. This material is intended for everyone, the only condition is the ability to work on the Linux command line.



Command line scripts are collections of the same commands that can be entered from the keyboard, collected into files and united by some common purpose. In this case, the results of the teams’ work can either be of independent value or serve as input data for other teams. Scripts are a powerful way to automate frequently performed actions.

So, if we talk about the command line, it allows you to execute several commands at once by entering them separated by a semicolon:

Pwd; whoami
In fact, if you tried this in your terminal, your first bash script involving two commands has already been written. It works like this. First, the pwd command displays information about the current working directory, then the whoami command displays information about the user under which you are logged in.

Using this approach, you can combine as many commands as you like on one line, the only limit is the maximum number of arguments that can be passed to the program. You can define this limit using the following command:

Getconf ARG_MAX
Command line - great tool, but commands have to be entered into it every time they are needed. What if we wrote a set of commands into a file and simply called that file to execute them? In fact, the file we are talking about is called a command line script.

How bash scripts work

Create an empty file using the touch command. Its first line needs to indicate which shell we are going to use. We are interested in bash , so the first line of the file will be like this:

#!/bin/bash
Other lines in this file use the hash symbol to indicate comments that the shell does not process. However, the first line is a special case, there is a hash followed by Exclamation point(this sequence is called a shebang) and the path to bash indicate to the system that the script was created specifically for bash.

Shell commands are separated by a line feed, comments are separated by a hash sign. This is what it looks like:

#!/bin/bash # This is a comment pwd whoami
Here, just like on the command line, you can write commands on one line, separated by semicolons. However, if you write the commands on different lines, the file is easier to read. In any case, the shell will process them.

Setting script file permissions

Save the file and name it myscript and you're almost done creating your bash script. Now all that remains is to make this file executable, otherwise, if you try to run it, you will encounter a Permission denied error.


Attempting to run a script file with incorrectly configured permissions

Let's make the file executable:

Chmod +x ./myscript
Now let's try to execute it:

./myscript
After setting the permissions everything works as it should.


Successfully running bash script

Message output

To display text in Linux console The echo command is used. Let's use the knowledge of this fact and edit our script, adding explanations to the data that is output by the commands already in it:

#!/bin/bash # our comment is here echo "The current directory is:" pwd echo "The user logged in is:" whoami
This is what happens after running the updated script.


Outputting messages from a script

Now we can display explanatory notes using the echo command. If you don't know how to edit a file using Linux tools, or haven't encountered the echo command before, take a look at this resource.

Using Variables

Variables allow you to store information in a script file, such as the results of commands, for use by other commands.

There is nothing wrong with executing individual commands without storing their results, but this approach is quite limited in its capabilities.

There are two types of variables that can be used in bash scripts:

  • Environment Variables
  • User Variables

Environment Variables

Sometimes shell commands need to work with some system data. Here, for example, is how to display the home directory current user:

#!/bin/bash # display user home echo "Home for the current user is: $HOME"
Please note that we can use the $HOME system variable in double quotes, this will not prevent the system from recognizing it. This is what you get if you run the above scenario.


Using an environment variable in a script

What if you need to display a dollar sign on the screen? Let's try this:

Echo "I have $1 in my pocket"
The system will detect a dollar sign in a quoted string and assume that we have referenced a variable. The script will try to display the value of the undefined variable $1. This is not what we need. What to do?

In this situation, using the escape character, a backslash, before the dollar sign will help:

Echo "I have \$1 in my pocket"
The script will now output exactly what is expected.


Using an escape sequence to print a dollar sign

User Variables

In addition to environment variables, bash scripts allow you to define and use your own variables in the script. Such variables hold a value until the script completes execution.

As with system variables, user variables can be accessed using the dollar sign:
TNW-CUS-FMP - promo code for a 10% discount on our services, available for activation within 7 days
#!/bin/bash # testing variables grade=5 person="Adam" echo "$person is a good boy, he is in grade $grade"
This is what happens after running such a script.


Custom Variables in a Script

Command Substitution

One of the most useful features of bash scripts is the ability to extract information from command output and assign it to variables, allowing that information to be used anywhere in the script file.

There are two ways to do this.

  • Using the backtick "`"
  • Using the $() construct
When using the first approach, be careful not to include a single quotation mark in place of the backtick. The command must be enclosed in two such icons:

Mydir=`pwd`
In the second approach, the same thing is written like this:

Mydir=$(pwd)
And the script might end up looking like this:

#!/bin/bash mydir=$(pwd) echo $mydir
During its operation, the output of the pwd command will be stored in the mydir variable, the contents of which, using the echo command, will be sent to the console.


A script that saves the results of a command in a variable

Mathematical operations

To perform mathematical operations in a script file, you can use a construct like $((a+b)) :

#!/bin/bash var1=$((5 + 5)) echo $var1 var2=$(($var1 * 2)) echo $var2


Mathematical Operations in a Script

if-then control construct

In some scenarios, you need to control the flow of command execution. For example, if a certain value is greater than five, you need to perform one action, otherwise, another. This is applicable in many situations, and here the if-then control construct will help us. In the most in simple form it looks like this:

If command then fi commands
Here's a working example:

#!/bin/bash if pwd then echo "It works" fi
In this case, if the pwd command completes successfully, the text “it works” will be printed to the console.

Let's use the knowledge we have and write a more complex script. Let's say we need to find a certain user in /etc/passwd, and if we were able to find him, report that he exists.

#!/bin/bash user=likegeeks if grep $user /etc/passwd then echo "The user $user Exists" fi
This is what happens after running this script.


Search for a user

Here we have used the grep command to search for the user in the /etc/passwd file. If the grep command is unfamiliar to you, its description can be found.

In this example, if the user is found, the script will display a corresponding message. What if the user could not be found? In this case, the script will simply complete execution without telling us anything. We'd like him to tell us about this too, so we'll improve the code.

if-then-else control construct

In order for the program to be able to report both the results of a successful search and failure, we will use the if-then-else construct. Here's how it works:

If command then commands else commands fi
If the first command returns zero, which means it was executed successfully, the condition will be true and execution will not proceed along the else branch. Otherwise, if something other than zero is returned, that would indicate failure, or false result, the commands located after else will be executed.

Let's write the following script:

#!/bin/bash user=anotherUser if grep $user /etc/passwd then echo "The user $user Exists" else echo "The user $user doesn’t exist" fi
Its execution went along the else branch.


Running a script with an if-then-else construct

Well, let's move on and ask ourselves about more difficult conditions. What if you need to check not one condition, but several? For example, if desired user found, you need to display one message, if some other condition is met - another message, and so on. In such a situation, nested conditions will help us. It looks like this:

If command1 then commands elif command2 then commands fi
If the first command returns zero, what does it mean? successful completion, the commands in the first then block will be executed, otherwise, if the first condition is false and if the second command returns zero, the second block of code will be executed.

#!/bin/bash user=anotherUser if grep $user /etc/passwd then echo "The user $user Exists" elif ls /home then echo "The user doesn’t exist but anyway there is a directory under /home" fi
In such a script, you can, for example, create a new user using the useradd command if the search does not produce results, or do something else useful.

Comparison of numbers

In scripts you can compare numeric values. Below is a list of relevant commands.
n1 -eq n2 Returns true if n1 equals n2 .
n1 -ge n2 Returns true if n1 is greater than or equal to n2 .
n1 -gt n2 Returns true if n1 is greater than n2 .
n1 -le n2 Returns true if n1 is less than or equal to n2 .
n1 -lt n2 Returns true if n1 is less than n2 .
n1 -ne n2 Returns true if n1 is not equal to n2 .

As an example, let's try one of the comparison operators. Note that the expression is enclosed in square brackets.

#!/bin/bash val1=6 if [ $val1 -gt 5 ] then echo "The test value $val1 is greater than 5" else echo "The test value $val1 is not greater than 5" fi
This is what this command will output.


Comparison of numbers in scripts

The value of the val1 variable is greater than 5, as a result the then branch of the comparison operator is executed and a corresponding message is displayed in the console.

String comparison

Scripts can also compare string values. Comparison operators look quite simple, but string comparison operations have certain features, which we will touch on below. Here is a list of operators.
str1 = str2 Tests strings for equality, returning true if the strings are identical.
s tr1 != str2 Returns true if the strings are not identical.
str1< str2 Возвращает истину, если str1 меньше, чем str2 .
str1 > str2 Returns true if str1 is greater than str2 .
-n str1 Returns true if the length of str1 is greater than zero.
-z str1 Returns true if the length of str1 is zero.

Here's an example of comparing strings in a script:

#!/bin/bash user ="likegeeks" if [$user = $USER] then echo "The user $user is the current logged in user" fi
As a result of executing the script, we get the following.


Comparing strings in scripts

Here's one feature of string comparison that's worth mentioning. Namely, the operators ">" and "<» необходимо экранировать с помощью обратной косой черты, иначе скрипт будет работать неправильно, хотя сообщений об ошибках и не появится. Скрипт интерпретирует знак «>» as an output redirection command.

Here's what working with these operators looks like in code:

#!/bin/bash val1=text val2="another text" if [ $val1 \>
Here are the results of the script.


String comparison, warning given

Please note that the script, although executed, issues a warning:

./myscript: line 5: [: too many arguments
To get rid of this warning, we enclose $val2 in double quotes:

#!/bin/bash val1=text val2="another text" if [ $val1 \> "$val2" ] then echo "$val1 is greater than $val2" else echo "$val1 is less than $val2" fi
Now everything works as it should.


String comparison

Another feature of the operators “>” and “<» заключается в том, как они работают с символами в верхнем и нижнем регистрах. Для того, чтобы понять эту особенность, подготовим text file with this content:

Likegeeks likegeeks
Let's save it, giving it the name myfile , and then run the following command in the terminal:

Sort myfile
It will sort the lines from the file like this:

Likegeeks Likegeeks
The sort command, by default, sorts strings in ascending order, that is, the lowercase letter in our example is smaller than the uppercase one. Now let's prepare a script that will compare the same strings:

#!/bin/bash val1=Likegeeks val2=likegeeks if [ $val1 \> $val2 ] then echo "$val1 is greater than $val2" else echo "$val1 is less than $val2" fi
If you run it, it turns out that everything is the other way around - the lowercase letter is now larger than the uppercase one.


The sort command and comparing strings in a script file

In comparison commands, uppercase letters are smaller than lowercase letters. String comparison here is done by comparing the ASCII codes of the characters, the sort order thus depends on the character codes.

The sort command, in turn, uses the sort order specified in the system language settings.

File checks

Perhaps the following commands are used most often in bash scripts. They allow you to check various conditions regarding files. Here is a list of these commands.
-d file Checks whether the file exists and is a directory.
-e file Checks if the file exists.
-f file Checks whether the file exists and is a file.
-r file Checks whether the file exists and is readable.
-s file Checks if the file exists and is not empty.
-w file Checks whether the file exists and is writable.
-x file Checks whether the file exists and is executable.
file1 -nt file2 Checks if file1 is newer than file2 .
file1 -ot file2 Checks if file1 is older than file2 .
-O file Checks whether the file exists and is owned by the current user.
-G file Checks whether a file exists and whether its group ID matches the current user's group ID.

These commands, as well as many others discussed today, are easy to remember. Their names, being abbreviations of various words, directly indicate the checks they perform.

Let's try one of the commands in practice:

#!/bin/bash mydir=/home/likegeeks if [ -d $mydir ] then echo "The $mydir directory exists" cd $ mydir ls else echo "The $mydir directory does not exist" fi
This script, for an existing directory, will display its contents.


Listing the contents of a directory

We believe that you can experiment with the remaining commands yourself; they are all used according to the same principle.

Results

Today we talked about how to get started writing bash scripts and covered some basic things. In fact, the topic of bash programming is huge. This article is a translation of the first part of a large series of 11 materials. If you want to continue right now, here is a list of the originals of these materials. For convenience, the translation of which you just read is included here.

Writing scripts in Linux (learning with examples)

———————————————————————————-

1. Introduction

What you need to write scripts
Knowledge of command line tools and their required options.
Basic knowledge in English elementary school level will not hurt.

Why are scripts needed?
Firstly, administering a Linux server to one degree or another comes down to systematically executing the same commands. Moreover, it is not necessary that these commands be carried out by a person. They can be programmed to be executed by a machine.
Secondly, even just performing a regular task, which (suddenly) amounts to 20-1000... monotonous operations is MUCH easier to implement in a script.

What is a script
A script is a set of instructions that must be in a certain order and in certain time execute computer. Instructions can be like internal teams shells (cycles, conditions, processing text information, work with environment variables etc.), as well as any program we execute in the console with the necessary parameters.

How to write a script
In our case, the script will be a text file with execution attributes. If a script file begins with the sequence #!, which in the UNIX world is called sha-bang, then this tells the system which interpreter to use to execute the script. If this is difficult to understand, then just remember that we will start writing all scripts with the line #!/bin/bash or #!/bin/sh, and then the commands and comments for them will follow.

Parting words
I sincerely advise you to write as many comments as possible on almost every line in the script. Time will pass and you will need to change or modernize the script you once wrote. If you don’t remember or don’t understand what is written in the script, then it becomes difficult to change it; it’s easier to write from scratch.

What scripts might we need:

    setting firewall rules when the system boots.
    performing backup of settings and data.
    adding mailboxes to the mail server (more precisely to the mysql database)
    launching at a certain time (preferably every night) a program that scans the proxy server logs and produces a convenient web report on the amount of downloaded traffic.
    sending us information by email that someone has accessed our server via ssh, connection time and client address.

About the method of writing scripts
We create a text file, edit it, set execution rights, run it, look for errors, correct it, run it, look for errors...
When everything is polished and working correctly, we put it in autoload or in the scheduler for a certain time.

———————————————————————————-

2. Learning to write scripts in the internal BASH language
original: https://www.linuxconfig.org/Bash_scripting_Tutorial

This tutorial assumes no prior knowledge of how to write scripts using the internal Bash language. With the help of this guide, you will soon discover that writing scripts is a very simple task. Let's start our tutorial with a simple script that prints the string "Hello World!" (translated from English - Hello everyone!)

1. Scenario “Hello everyone”
Here's your first bash script example:

#!/bin/bash
echo "Hello World"

Let's go to the directory containing our hello_world.sh file and make it executable:

Code: Select all $ chmod +x hello_world.sh

Running the script for execution

Code: Select all $ ./hello_world.sh

2. Simple archiving bash script

#!/bin/bash
tar -czf myhome_directory.tar.gz /home/user

Code: Select all $ ./backup.sh

$ du -sh myhome_directory.tar.gz
41M myhome_directory.tar.gz

3. Working with variables
IN in this example we declare a simple variable and display it on the screen using the echo command

#!/bin/bash
STRING=”HELLO WORLD!!!”
echo $STRING

Code: Select all $ ./hello_world.sh
HELLO WORLD!!!

Our archiving script with variables:

#!/bin/bash
OF=myhome_directory_$(date +%Y%m%d).tar.gz
IF=/home/user
tar -czf $OF $IF

Code: Select all $ ./backup.sh
tar: Removing leading "\" from member names
$ du -sh *tar.gz
41M myhome_directory_20100123.tar.gz

3.1 Global and local variables

#!/bin/bash
# Declare a global variable
# Such a variable can be used anywhere in this script
VAR="global variable"
function bash(
# Declare a local variable
# Such a variable is only valid for the function in which it was declared
local VAR=”local variable”
echo $VAR
}
echo $VAR
bash
# Note that the global variable has not changed
echo $VAR

Code: Select all $ ./variables.sh
global variable
local variable
global variable

4. Pass arguments to the script

#!/bin/bash
# Use predefined variables to access arguments
# Print arguments to screen
echo $1 $2 $3 ‘ -> echo $1 $2 $3’

#We can also access arguments through a special array args=("$@")
# Print arguments to screen
echo $(args) $(args) $(args) ‘ -> args=(“$@”); echo $(args) $(args) $(args)’

# Use $@ to print all arguments at once
echo $@ ‘ -> echo $@’

Use the $# variable to display the number of arguments passed to the script
echo Number of arguments passed: $# ‘ -> echo Number of arguments passed: $#’

Code: Select all $ ./arguments.sh Bash Scripting Tutorial
Bash Scripting Tutorial -> echo $1 $2 $3
Bash Scripting Tutorial -> args=("$@"); echo $(args) $(args) $(args)
Bash Scripting Tutorial -> echo $@
Number of arguments passed: 3 -> echo Number of arguments passed: $#

5. Executing shell commands in a script

#!/bin/bash
# use backquotes " ` ` " to execute a shell command
echo `uname -o`
# now let's try without quotes
echo uname -o

Code: Select all $ uname -o
GNU/Linux
$ ./bash_backtricks.sh
GNU/Linux
uname -o

As you can see, in the second case the command itself was displayed, and not the result of its execution

6. Reading user input (interactivity)

#!/bin/bash
echo -e "Hi, please type the word: \c "
read word
echo "The word you entered is: $word"
echo -e “Can you please enter two words? »
read word1 word2
echo "Here is your input: \"$word1\" \"$word2\""
echo -e “How do you feel about bash scripting? »
# read command now stores a reply into the default build-in variable $REPLY
read
echo “You said $REPLY, I’m glad to hear that! »
echo -e “What are your favorite colors? »
# -a makes read command to read into an array
read -a colors
echo “My favorite colors are also $(colours), $(colours) and $(colours):-)”

Code: Select all $ ./read.sh
Hi, please type the word: something
The word you entered is: something
Can you please enter two words?
Debian Linux
Here is your input: "Debian" "Linux"
How do you feel about bash scripting?
good
You said good, I"m glad to hear that!
What are your favorite colors?
blue green black
My favorite colors are also blue, green and black:-)

7. Using a trap

#!/bin/bash
# declare a trap
trap bashtrap INT
# clear the screen
clear;
# The hook function is executed when the user presses CTRL-C:
# The screen will display => Executing bash trap subrutine !
# but the script will continue to run
bashtrap()
{
echo "CTRL+C Detected !…executing bash trap !"
}
# the script will count up to 10
for a in `seq 1 10`; do
echo "$a/10 to Exit."
sleep 1;
done
echo "Exit Bash Trap Example!!!"

Code: Select all $ ./trap.sh
1/10
2/10
3/10
4/10
5/10
6/10

7/10
8/10
9/10
CTRL+C Detected !...executing bash trap !
10/10
Exit Bash Trap Example!!!

As you can see, the Ctrl-C key combination did not stop the execution of the script.

8. Arrays
8.1 Declaring a simple array

#!/bin/bash
# Declare a simple array with 4 elements
ARRAY=('Debian Linux' 'Redhat Linux' Ubuntu Linux)
# Get the number of elements in the array
ELEMENTS=$(#ARRAY[@])

# loop through each element of the array
for ((i=0;i<$ELEMENTS;i++)); do
echo $(ARRAY[$(i)])
done

Code: Select all $./arrays.sh
Debian Linux
Redhat Linux
Ubuntu
Linux

8.2 Filling the array with values ​​from the file

#!/bin/bash
# Declare an array
declare -a ARRAY
# exec command # stdin (usually the keyboard) will be derived from this file. This makes it possible to read
# the contents of the file, line by line, and parse each line entered using sed and/or awk.
exec 10 let count=0

while read LINE<&10; do

ARRAY[$count]=$LINE
((count++))
done

echo Number of elements: $(#ARRAY[@])
# Print array values
echo $(ARRAY[@])
# close the file
exec 10>&-

Code: Select all $ cat bash.txt
Debian Linux
Redhat Linux
Ubuntu
Linux
$ ./arrays.sh
Number of elements: 4
Debian Linux Redhat Linux Ubuntu Linux

9. If-then-else conditions
9.1. Simple use of "if-else" conditions
Pay attention to the spaces in the square brackets, without which the condition will not work.

#!/bin/bash
directory="./BashScripting"

# check for directory presence
if [ -d $directory ]; then
echo "Directory exists"
else
echo "Directory does not exist"
fi

Code: Select all $ ./if_else.sh
Directory does not exist
$ mkdir BashScripting
$ ./if_else.sh
Directory exists

9.2 Nested if-else conditions

#!/bin/bash
# Declare a variable with the value 4
choice=4
# Display
echo "1. Bash"
echo "2. Scripting"
echo "3. Tutorial"

# Execute while the variable is equal to four
# Looping
while [ $choice -eq 4 ]; do

# read user input
read choice
# nested if-else condition
if [ $choice -eq 1 ] ; then

echo "You have chosen word: Bash"

if [ $choice -eq 2 ] ; then
echo “You have chosen word: Scripting”
else

if [ $choice -eq 3 ] ; then
echo “You have chosen word: Tutorial”
else
echo "Please make a choice between 1-3 !"
echo "1. Bash"
echo "2. Scripting"
echo "3. Tutorial"
echo -n “Please choose a word? »
choice=4
fi
fi
fi
done

Code: Select all $ ./nested.sh
1. Bash
2. Scripting
3. Tutorial

5

1. Bash
2. Scripting
3. Tutorial
Please choose a word?
4
Please make a choice between 1-3 !
1. Bash
2. Scripting
3. Tutorial
Please choose a word?
3
You have chosen word: Tutorial

Thus, the body of the “while” loop is executed first, because the choice variable is initially equal to four. Then we read the user input into it, and if the input is not equal to 1,2 or 3, then we make our variable equal to 4 again, and therefore the body of the loop is repeated (you must enter 1,2 or 3 again).

10. Comparisons
10.1 Arithmetic comparisons

Lt<
-gt>
-le<=
-ge >=
-eq ==
-ne !=

#!/bin/bash

NUM1=2
NUM2=2
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values ​​are equal"
else
echo "Values ​​are NOT equal"
fi

Code: Select all $ ./equals.sh
Both Values ​​are equal

#!/bin/bash
# Declare variables with integer values
NUM1=2
NUM2=3
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values ​​are equal"
else
echo "Values ​​are NOT equal"
fi

Code: Select all $ ./equals.sh
Values ​​are NOT equal

#!/bin/bash
# Declare variables with integer values
NUM1=2
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values ​​are equal"
elif [ $NUM1 -gt $NUM2 ]; then
echo "$NUM1 is greater then $NUM2"
else
echo "$NUM2 is greater then $NUM1"
fi

Code: Select all $ ./equals.sh
2 is greater then 1

10.2 Character-text comparisons

The same
!= not the same
< меньще чем
> more than
-n s1 variable s1 is not empty
-z s1 variable s1 is empty

#!/bin/bash

S1="Bash"

S2="Scripting"
if [ $S1 = $S2 ]; then

else
echo "Strings are NOT equal"
fi

Code: Select all $ ./statement.sh
Strings are NOT equal

#!/bin/bash
# Declare the character variable S1
S1="Bash"
# Declare the character variable S2
S2=”Bash”
if [ $S1 = $S2 ]; then
echo "Both Strings are equal"
else
echo "Strings are NOT equal"
fi

Code: Select all $ ./statement.sh
Both Strings are equal

11. Checking files

B filename Block special file
-c filename Special character file
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-G filename Check if file exists and is owned by effective group ID.
-g filename true if file exists and is set-group-id.
-k filename Sticky bit
-L filename Symbolic link
-O filename True if file exists and is owned by the effective user id.
-r filename Check if file is a readable
-S filename Check if file is socket
-s filename Check if file is nonzero size
-u filename Check if file set-ser-id bit is set
-w filename Check if file is writable
-x filename Check if file is executable

#!/bin/bash
file="./file"
if [ -e $file ]; then
echo "File exists"
else
echo "File does not exist"
fi

Code: Select all $ ls
file.sh
$ ./file.sh
File does not exist
$ touch file
$ls
file file.sh
$ ./file.sh
File exists

Similarly, for example, we can use "while" loops to check if the file does not exist. This script will sleep until the file exists. Note the Bash negator "!" which negates (inverts) the -e option.

12. Cycles
12.1. For loop

#!/bin/bash
# for loop
for f in $(ls /var/); do
echo $f
done

Running a for loop from the bash command line:

Code: Select all $ for f in $(ls /var/); do echo $f; done Code: Select all $ for f in $(ls /var/); do echo $f; done
backups
cache
crash
games
lib
local
lock
log
mail
opt
run
spool
tmp
www

12.2. While loop

#!/bin/bash
COUNT=6
# while loop
while [ $COUNT -gt 0 ]; do

let COUNT=COUNT-1
done

Code: Select all $ ./while_loop.sh
Value of count is: 6
Value of count is: 5
Value of count is: 4
Value of count is: 3
Value of count is: 2
Value of count is: 1

12.3. Until loop

#!/bin/bash
COUNT=0
# until loop
until [ $COUNT -gt 5 ]; do
echo Value of count is: $COUNT
let COUNT=COUNT+1
done

Code: Select all $ ./until_loop.sh
Value of count is: 0
Value of count is: 1
Value of count is: 2
Value of count is: 3
Value of count is: 4
Value of count is: 5

12.4. Loops with Implicit Conditions
In the following example, the while loop condition is the presence of standard input.
The body of the loop will be executed as long as there is something to redirect from standard output to the read command.

#!/bin/bash
# This script will search for and remove spaces
# in files, replacing them with underscores
DIR="
Controlling a loop with the read command by redirecting output within the loop.
find $DIR -type f | while read file; do
# use the POSIX [:space:] class to find spaces in filenames
if [[ "$file" = *[[:space:]]* ]]; then
# replace spaces with underscores
mv "$file" `echo $file | tr ‘ ‘ ‘_’`
fi;
done

Code: Select all $ ls -1
script.sh
$ touch "file with spaces"
$ls -1
file with spaces
script.sh
$ ./script.sh
$ls -1
file_with_spaces
script.sh

13. Functions

#!/bin/bash
# Functions can be declared in any order
function function_B(
echo Function B.
}
function function_A (
echo $1
}
function function_D(
echo Function D.
}
function function_C(
echo $1
}
# Call functions
# pass the parameter to the function function A
function_A "Function A."
function_B
# pass the parameter to the function function C
function_C "Function C."
function_D

Code: Select all $ ./functions.sh
Function A.
Function B.
Function C.
Function D.

14. Selection operator - Select

#!/bin/bash
PS3=’Choose one word: ‘
#select
select word in "linux" "bash" "scripting" "tutorial"
do
echo "The word you have selected is: $word"
# Abort, otherwise the loop will be endless.
break
done
exit 0

Code: Select all $ ./select.sh
1) linux
2) bash
3) scripting
4) tutorial
Choose one word: 4
The word you have selected is: tutorial

15. Selection operator - Case

#!/bin/bash
echo "What is your preferred programming / scripting language"
echo "1) bash"
echo "2)perl"
echo "3) phyton"
echo "4) c++"
echo “5) I don’t know!”
read case;
# simple case-selection structure
# note that in this example $case is just a variable
# and doesn't have to be called that. This is just an example
case $case in
1) echo “You selected bash”;;
2) echo “You selected perl”;;
3) echo “You selected phyton”;;
4) echo “You selected c++”;;
5) exit
esac

Code: Select all $ ./case.sh
What is your preferred programming / scripting language
1) bash
2) perl
3)phyton
4) c++
5) I don't know!
4
You selected c++

———————————————————————————-

More detailed information can be obtained from various sources, for example here
original: https://www.linuxconfig.org/Bash_scripting_Tutorial
https://ruslandh.narod.ru/howto_ru/Bash-Prog-Intro/
https://bug.cf1.ru/2005-03-17/programmin … -book.html

https://ubuntologia.ru/forum/viewtopic.php?f=109&t=2296