We write scripts in Linux (learning by examples). Writing scripts in Bash How to create scripts in Ubuntu

Writing scripts in Linux (learning with examples)

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

1. Introduction

What you need to write scripts
Tool Proficiency command line and their necessary 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 a computer must execute in a certain order and at a certain time. Instructions can be either internal shell commands (cycles, conditions, processing text information, working with environment variables, etc.), or any program that we execute in the console with the necessary parameters.

How to write a script
In our case, the script will be 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.
    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 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

For writing a simple bash script, we need to perform the following simple steps:

How it all works:

The first line of our script #!/bin/bash is essential for our script to execute successfully.

second line mkdir testdir creates the testdir directory

the third line cd testdir allows you to go to the created directory testdir

team touch in the next line touch file1 file2 file3 creates three files

and the last command in the line of our script, ls -al, allows you to display the contents of the current directory, in which, thanks to the previous line, three empty files have appeared.

As we see, in our simple script all commands start on a new line. Each line, when running the script, sequentially performs its work, performing certain actions.

If you daily execute a chain of any identical commands (with constant parameters) in Linux, then perhaps it makes sense for you to write the same simple bash script, which will allow you to save your time and automate your work.

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 on the operating system. To write 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, let's open 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 a compatible command line interpreter that passes "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 the 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 the created file with the script from the file manager (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: , then a text editor to create a script.
For example, I made the following blank.

In a 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 of the 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 add as many programs as you like into this line, separated by a space, the main thing is that they are composed 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 the future, for possible reinstallation of the system and re-configuration, best on a separate partition of the hard drive in the folder /home. If there is none, then in a cloud service (Cloud data storage) like: 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.

No matter how simple the graphical interface in Linux is and no matter how many functions there are, there are still tasks that are more convenient to solve through the terminal. Firstly, because it is faster, and secondly, not all machines have a graphical interface, for example, on servers all actions are performed through the terminal in order to save computing resources.

If you are already a more experienced user, you probably often perform various tasks through the terminal. There are often tasks for which you need to run several commands in turn, for example, to update the system, you must first update the repositories, and only then download new versions of packages. This is just an example and there are a lot of such actions, even taking backup and uploading copied files to a remote server. Therefore, in order not to type the same commands several times, you can use scripts. In this article we will look at writing scripts in Bash, look at the basic operators, as well as how they work, so to speak, Bash scripts from scratch.

A script, or as it is also called, a script, is a sequence of commands that are read and executed in turn by an interpreter program, in our case it is a command line program - bash.

A script is a regular text file that lists the usual commands that we are used to entering manually, as well as the program that will execute them. The loader that will execute the script does not know how to work with environment variables, so it needs to be passed the exact path to the program that needs to be launched. And then it will transfer your script to this program and execution will begin.

A simple example of a Bash shell script:

!/bin/bash
echo "Hello world"

The echo utility displays the string passed to it as a parameter to the screen. The first line is special, it specifies the program that will execute the commands. Generally speaking, we can create a script in any other programming language and specify the desired interpreter, for example, in python:

!/usr/bin/env python
print("Hello world")

Or in PHP:

!/usr/bin/env php
echo "Hello world";

In the first case, we directly pointed to the program that will execute the commands; in the next two, we do not know the exact address of the program, so we ask the env utility to find it by name and run it. This approach is used in many scripts. But that is not all. On a Linux system, in order for the system to execute a script, you need to set the executable flag on the file with it.

This flag does not change anything in the file itself, it only tells the system that this is not just a text file, but a program and it needs to be executed, open the file, recognize the interpreter and execute it. If no interpreter is specified, the user's interpreter will be used by default. But since not everyone uses bash, you need to specify this explicitly.

To do:

chmod ugo+x script_file

Now let's run our little first program:

./script_file

Everything is working. You already know how to write a small script, say for updating. As you can see, the scripts contain the same commands that are executed in the terminal, and they are very easy to write. But now we'll complicate things a little. Since a script is a program, it needs to make some decisions on its own, store the results of command execution, and execute loops. The Bash shell allows you to do all this. True, everything is much more complicated here. Let's start with something simple.

Variables in scripts

Writing scripts in Bash is rarely complete without saving temporary data, which means creating variables. Not a single programming language can do without variables, including our primitive command shell language.

You may have come across environment variables before. So, these are the same variables and they work in the same way.

For example, let's declare a string variable:

string="Hello world"

The value of our string is in quotes. But in reality, quotation marks are not always necessary. The main principle of bash is preserved here - a space is a special character, a delimiter, so if you do not use quotes, world will already be considered a separate command, for the same reason we do not put spaces before and after the equal sign.

The $ symbol is used to display the value of a variable. For example:

Let's modify our script:

!/bin/bash
string1="hello"
string2=world
string=$string1$string2
echo $string

And we check:

Bash doesn't distinguish between variable types in the same way that high-level languages ​​like C++ do; you can assign either a number or a string to a variable. Equally, all this will be considered a string. The shell only supports string merging; to do this, simply write the variable names in a row:

!/bin/bash
string1="hello"
string2=world
string=$string1$string2\ and\ me
string3=$string1$string2" and me"
echo $string3

We check:

Please note that as I said, quotes are optional if there are no special characters in the string. Take a closer look at both methods of merging strings, they also demonstrate the role of quotes. If you need more complex string processing or arithmetic operations, this is not included in the shell's capabilities; regular utilities are used for this.

Variables and Command Output

Variables wouldn't be so useful if they couldn't store the results of running utilities. The following syntax is used for this:

$(team )

With this design, the output of the command will be redirected directly to where it was called from, rather than to the screen. For example, the date utility returns the current date. These commands are equivalent:

Do you understand? Let's write a script that displays hello world and the date:

string1="hello world"
string2=$(date)

string=$string1$string2

Now you know enough about variables that you're ready to create a bash script, but there's more to come. Next we will look at parameters and control structures. Let me remind you that these are all regular bash commands, and you don’t have to save them in a file; you can execute them right away on the fly.

Script parameters

It is not always possible to create a bash script that does not depend on user input. In most cases, you need to ask the user what action to take or what file to use. When calling a script, we can pass parameters to it. All these parameters are available as variables named as numbers.

A variable named 1 contains the value of the first parameter, variable 2 contains the value of the second, and so on. This bash script will print the value of the first parameter:

!/bin/bash
echo $1

Control constructs in scripts

Creating a bash script would not be as useful without the ability to analyze certain factors and perform the necessary actions in response to them. This is quite a complex topic, but it is very important in order to create a bash script.

In Bash, there is a command to check conditions. Its syntax is as follows:

if command_condition
then
team
else
team
fi

This command checks the exit code of the condition command, and if 0 (success) then executes the command or several commands after the word then, if the exit code is 1, the else block is executed, fi means the end of the command block.

But since we are most often interested not in the return code of a command, but in the comparison of strings and numbers, the [[ command was introduced, which allows you to perform various comparisons and issue a return code depending on the result of the comparison. Its syntax is:

[[ parameter1 operator parameter2 ]]

For comparison, we use the operators already familiar to us<,>,=,!= etc. If the expression is true, the command will return 0, if not - 1. You can test its behavior a little in the terminal. The return code of the last command is stored in the $? variable:

Now, combining all this, we get a script with a conditional expression:

!/bin/bash
if [[ $1 > 2 ]]
then
echo $1" is greater than 2"
else
echo $1" is less than 2 or 2"
fi

Of course, this design has more powerful capabilities, but it is too complex to cover them in this article. Perhaps I'll write about this later. For now, let's move on to cycles.

Loops in scripts

The advantage of the programs is that we can indicate in a few lines what actions need to be performed several times. For example, it is possible to write bash scripts that consist of only a few lines, but run for hours, analyzing parameters and performing the necessary actions.

Let's look at the for loop first. Here is its syntax:

for variable in list
do
team
done

Iterates through the entire list and assigns a value from the list to a variable one by one, after each assignment it executes the commands located between do and done.

For example, let's look at five numbers:

for index in 1 2 3 4 5
do
echo $index
done

Or you can list all files from the current directory:

for file in $(ls -l); do echo "$file"; done

As you understand, you can not only display names, but also perform the necessary actions, this is very useful when creating a bash script.

The second loop we'll look at is the while loop, which runs until the condition command returns code 0, success. Let's look at the syntax:

while command condition
do
team
done

Let's look at an example:

!/bin/bash
index=1
while [[ $index< 5 ]]
do
echo $index
let "index=index+1"
done

As you can see, everything is done, the let command simply performs the specified mathematical operation, in our case increasing the value of the variable by one.

I would like to point out one more thing. Constructs such as while, for, if are designed to be written on several lines, and if you try to write them on one line, you will get an error. But nevertheless, this is possible; to do this, put a semicolon ";" where there should be a line break. For example, the previous loop could be executed as a single line:

index=1; while [[ $index< 5 ]]; do echo $index; let "index=index+1"; done;

Everything is very simple, I tried not to complicate the article with additional terms and capabilities of bash, just the most basic things. In some cases, you may need to make a gui for a bash script, then you can use programs such as zenity or kdialog, with the help of them it is very convenient to display messages to the user and even request information from him.

conclusions

Now you understand the basics of creating a script in Linux and can write the script you need, for example, for backup. I tried to review bash scripts from scratch. Therefore, not all aspects have been considered. Perhaps we will return to this topic in one of the following articles.

In the community of system administrators and ordinary Linux users, the practice of writing Bash scripts is often famous in order to facilitate and simplify the execution of specific goals in the Linux operating system. In this article we will look at writing scripts in Bash, look at the basic operators, as well as how they work, so to speak, Bash scripts from scratch. Simply put, you once wrote the order of events that need to be done, wrote down the data, and so on, and then easily and simply write a single small command and all procedures are carried out as necessary.

It is possible to go even further and schedule the automatic execution of a script. If you are already a more experienced user, then, most likely, you quite often accomplish various goals through the terminal. This is just an example and there are a lot of such actions, even taking backup and uploading copied files to a remote server. There are often tasks for which you need to run several commands in turn, for example, to update the system, you must first update the repositories, and only then download new versions of packages.

This is a command shell where you have the opportunity to issue different commands that will begin to carry out various work at high speed and fruitfully. Absolutely all the power of the Linux OS is in the use of the terminal. Therefore, in order not to type the same commands several times, you can use scripts. This is very convenient, you simply combine several commands that have some effect, and then execute them with the same command or even using a shortcut. For the Linux operating system, many scripts have been created that are executed in various command shells. Well, in principle, you obviously already understand this.

The operating system considers as executable only those files that are assigned the executability characteristic. And the interpreter pronounces line by line in a row and executes all the directives that are present in the file. But if the executability characteristic is set for them, then a specialized computer program is used to launch them - an interpreter, in particular, the bash shell. We can run it like any other program using a terminal server, or we can execute a shell and tell it which file to execute.

In this case, you don't even need an executability flag. Instead, file start signatures and special flags are used. We have several different methods to enable script in Linux OS. Linux OS practically does not use a file extension to determine its type at the system level. File managers can do this, but not always. The operating system considers as executable only those files that are assigned the executability characteristic. These are ordinary files that contain text.

Linux Bash Scripts for Dummies

The bash construct can be described in 7 obligations of a similar type: “calling the command interpreter - the body of the bash script - the end of the script.” Scripts are written with the support of various text editors, and they are stored as text computer data. But, to make it more convenient, I store them together with the “*.sh” extension. But let's look at all this with the example of a specific goal. There is a use that needs to be launched with a fairly large set of characteristics. You will need to start often, and you are too lazy to enter these characteristics every time. To be more specific, let’s see what this effect looks like:

/home/Admin/soft/sgconf/sgconf -s 10.10.10.1 -p 5555 -a Admin -w 112233 -u user -c 100

For this script, let's use the bash interpreter. The primary process you and I need is to call the interpreter. Open a text editor and write code.

Let's add this operation taking into account the entered variables:

/home/Admin/soft/sgconf/sgconf -s 10.10.10.1 -p 5555 -a Admin -w 112233 -u $user -c $cash

The text that we will enter into the logs will be like this: text=”The balance of the user “user” has been replenished with “cash” rubles in time”

The text argument varies depending on the user, cash and time variables

if [ -e /home/Admin/scripts/sgconf/sgconf.log] then echo text >> /home/Admin/scripts/sgconf/sgconf.log else echo text > /home/Admin/scripts/sgconf/sgconf.logfi

Now, when we need to deposit money to someone, we run the script with the command “sh sgconf.sh”, enter the name of the payer and the payment amount. No long lines, no headaches with constantly entering the same values.

Create a bash script in Linux OS

To write a simple script in bash, we need to perform the following ordinary procedures. Let's create a meaningless file on the Linux command line (we call it firstscript for example) and open it for editing in our favorite text editor (vi/vim, nano, gedit, and so on). To develop a script you will not need a lot of effort, but to sketch out a script (program), you will need to study various auxiliary literature. We will describe the basics of writing scripts, so let’s get started, but if you don’t know what a terminal is and how to use it, then this is the place for you. At the very start, in order to write bash, we need to create a directory for our scripts and a file where we will write everything, for this we open the terminal and create a directory.

Switch to the newly created directory

And create a file

sudo gedit script.sh

In my example, I will create a system update script and write it to this file. We will open the text editor gedit, I like vim more, but it won’t be generally accepted among you, so I’m showing it on the standard one.

sudo apt update;sudo apt full-upgrade;

Make the script file executable (if it is not already so). Running sh scripts from the command line is easy. Run bash script linux.

chmod +x script.sh

We run the script by simply specifying the path to it:

path/to/script.sh

If the script is in the current directory, then you need to specify ./ before the script file name:

Sometimes you need superuser rights to run a script, then just write the sudo command before the script:

sudo./script.shsudo path/to/script.sh

You can, of course, start the script by directly specifying the interpreter: sh, bash and others:

bash script.shsh path/to/script.sh

As you can see, starting a sh script in Linux is a fairly common task, even if you are not yet very familiar with the terminal. There are really a lot of scripts and you may need to run some of them. In this guide, we looked at useful Linux bash scripts that you can use when using the Linux OS. In this article, we looked at useful Linux bash scripts that you can use when working with the system. Some of them consist of several lines, a few are placed in one line. There are both minor snippets that you can use in your scripts, as well as full-fledged dialog scripts for working with them through the console.