We write a sh script. Bash Scripting Guide

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 of English at primary 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 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 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

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 go.

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.

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

How it all works:

The first line of our script is essential for our script to execute successfully.

the second line creates the testdir directory

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

team touch the next line creates three files

and the last command in the line of our script 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.

It often happens that it is necessary to automate some action. Bash scripts always come to the rescue!
Do not forget that in order for the script to be run, you need to change the access rights to it, adding the ability to execute the file.

1.I/O, redirection

#!/bin/bash # Any shell script always begins with the line #!/bin/bash (or #!/bin/sh) # Comments always begin with the sign # # To display a message, use the ECHO command echo "hello, world" # and this is an example of formatted output...

almost like in C printf "formatted output ten=%d line=%s float=%f hexadecimal_number=0x%X\n" 10 "line" 11.56 234 # example of reading keyboard input read A echo $A printf " you just entered the word: %s\n" "$A" #redirection, pipelines, getting the output of another program # example of generating a 10-letter password PASSWORD1=`cat /dev/urandom | tr -d -c ‘a-zA-Z0-9’ | fold -w 10 | head -1` echo Password=$PASSWORD1 #quotes of the form " give the result of outputting to the screen what is inside them (i.e. the #program or script written inside such quotes is executed and the result they print to #standard output is the result of the operation "backquotes" #in this case the result is the output of a pipeline of multiple programs.

Interesting bash scripts for Linux terminal lovers

#operation | stands for conveyor. Those. in our example: #cat /dev/urandom outputs the contents of the file /dev/urandom (a special file for generating pseudo-random numbers) to std.output. #tr performs translation, i.e. replaces some bytes with others (this is necessary to avoid the appearance of non-printable characters in the password) #fold splits what it received on standard input into lines 10 characters long and displays it on standard output #head -1 prints the first line what she received on standard input. # or like this: PASSWORD2=`cat /dev/urandom | tr -dc _A-Z-a-z-0-9 | head -c10` echo Password=$PASSWORD2

2. Arithmetic operations, cycles by number of times

#!/bin/bash A="10" B="5" C=`expr $A + $B` printf "A=10 B=5 C=expr \$A + \$B C=%d \n" "$C" # example of a loop through i I=0 while [ $I -lt 15 ] do printf "0x%02x " "$I" I=`expr $I + 1` done echo

3.Various types of checks

#!/bin/bash # example of checking the existence of a file # create a file test1 touch test1 # check the existence of a file test1 if [ -f test1 ] ; then echo "file test1 exists" fi # check for non-existence of file test2 if ! [ -f test2 ] ; then echo "file test2 does not exist" fi # quick reference to other command options # -d filename directory exists # -f filename file exists # -L filename symbolic link exists # -r, -w, -x file is readable, writable or execute # -s filename the file exists and has a non-zero length # f1 -nt f2 f1 is newer than f2 # f1 -ot f2 f1 is older than f2

Tags: bash, freebsd, shell

Leave a comment via:

How to write a simple bash script

How to run several commands sequentially or all at once? If you need to run several commands, then the symbol “ is placed between them ; "called metacharacter. The syntax is as follows command1;command2;command3

Commands separated by " ; » are performed sequentially. Shell waits for the next command and returns to the command prompt after the last command is executed.

Execute multiple commands simultaneously

To run multiple commands at once, put an ampersand "&" at the end of the command. For example, consider the beginning of the backup script:

# /root/ftpbackup.sh &

And your terminal is free for further use, you do not need to wait for the script /root/ftpbackup.sh to finish executing!

Using it all together

You may have thousands of *.bak files. But all you need to do is list the categories you want and put everything in /tmp/list:

# for d in "/home/sales /home/dbs /data1"; do find $d -iname “*.bak” >> /tmp/list; done &

Source

Learning BASH (Basics)

Date:2012-12-10

Learning to write scripts

For the most part, all Linux consists of scripts, so you just need to know this language.
At its core, it is just a set of Linux commands, combined using different constructs into a competent and well-thought-out code.

Let's create our first script.
To do this, simply open a text editor and fill the file with the following:

#!/bin/bash
who; date

Everything is simple here.
By nature, the sharp (#) sign is generally seen as the start of a comment, but here, starting on the first line, it tells us that the bash interpreter should be used.

1) Execute permissions must be given

chmod u+x bash1.sh

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/game

And move this file to one of the directories, unless of course you need to access it simply by name, and not by its full location.

Here we looked at how the script is created, then we need to understand a few things.

Whenever we write scripts, we will manipulate variables, redirect input and output, work with pipes, and perform mathematical calculations.

Variables

To define a new variable, just say:

#!/bin/bash
F=Ivan
I=Ivanov
O=Ivanich
#Output using:
echo "FIO $F $I $O"

Result

sh bash2.sh
FIO Ivan Ivanov Ivanich

View variables;
# set

BASH=/bin/bash
HISTFILE=/root/.bash_history
HISTFILESIZE=500
HISTSIZE=500
HOME=/root
SSH_CLIENT=’192.168.200.3 9382 22′
SSH_CONNECTION=’192.168.200.3 9382 192.168.200.252 22′

There is another very interesting and useful way to set a variable using ` `

#!/bin/bash
day=`date +%y%m%d`
# In the future, the $day variable can be inserted into a script, for example a backup

rsync -avz /root/data /root/backup.$day

As a result of executing such a script, a backup will appear indicating the date the backup was created.

Redirecting input and output.

> Redirection to a file with complete overwriting of the file contents
>> Redirect with an append to a file, to the end of existing content.
ls -al / > 123
And the command:
ls -al /home >> 123
Will list all files from the root and then append the contents of the Home directory after that
this redirection is called output redirection
Input redirection - content is redirected to the command.
sort< sort.txt
The sort command sorts alphabetically, as a result, the chaotically filled sort.txt file, after redirecting to the sort program, will be sorted alphabetically
sort< sort.txt | more — а построение в канал отобразит отсортированные данные постранично
sort< sort.txt | grep s | more — отсортирует и выведет все со знаком «S»

Another useful thing to know is passing the result of one command to another or several.
An example of this would be:

cat /var/log/maillog | grep blocked | more

1) cat - displays the entire log file
2) then this log file is passed to the grep command for processing, which outputs only Blocked, but since there are a lot of messages with this status, it is necessary to pass it to the more command
3) more - necessary for page-by-page viewing of data

This sequence of commands is called transmission in a channel, when data from one command is transferred to another for processing, and those to another, and so on until they take the desired form.

Mathematical calculations

The easiest way to do math on Linux is with the bc command.
In this case, you should not set the number of digits after floating point using scale

#!/bin/bash
var1=45
var2=22
var3=`echo «scale=3; $var1/$var2" | bc`
echo $var3

Plutonit.ru - Administration, configuration of Linux and Windows 2009 - 2018

Database Error: Table ‘a111530_forumnew.rlf1_users’ doesn’t exist

Home -> MyLDP -> E-books on Linux OS

Creating and running a script

We write a script and choose a name for it

A shell script is a sequence of commands that you can use repeatedly. Execution of this sequence is usually carried out by entering the name of the script on the command line. Additionally, with cron you can use scripts to automate tasks. Another use of scripts is the procedure for booting and stopping a UNIX system, when operations with daemons and services are defined in init scripts.

To create a shell script, open a new, empty file in your editor. You can use any text editor for this: vim, emacs, gedit, dtpad etc.; Any will do. However, you can choose a more advanced editor such as vim or emacs, since such editors can be configured to recognize shell and Bash syntax and can be a good help in avoiding mistakes that newbies often make, such as forgetting to close parentheses and using semicolons.

Type UNIX commands into a new, empty file just as you would at the command line. As discussed in the previous chapter (see the "Executing a Command" section), commands can be shell functions, built-in commands, UNIX commands, or other scripts.

Give your script a mnemonic name that says what the script does. Make sure your script name does not conflict with existing commands. To avoid any confusion, script names often end with the extension .sh. However, there may be other scripts with the same name you chose on your system. Using commands which, whereis and others, look for information about existing programs and files with this name:

which -a script_name whereis script_name locate script_name ( approx.

Writing scripts in Linux (learning with examples)

: instead, specify the name of your script).

Script script1.sh

In this example we use the command echo, built into Bash, which will inform the user what needs to be done before the output is given. It is highly recommended that users be informed about what the script does so that users were not nervous if it seemed to them that the script was not doing anything. We'll return to the topic of notifying users in Chapter 8, “Writing an Interactive Script.”

Fig.2.1. Script script1.sh

Write the same script for yourself. A good idea would be to create a directory in which your scripts will be located. Add this directory to the contents of the variable:

export PATH=”$PATH:~/scripts”

If you're just getting started with Bash, use a text editor that uses different colors for different shell constructs. Syntax highlighting is supported in vim, gvim, (x)emacs, kwrite and many other editors, see the documentation for your favorite editor.

Executing the script

In order for a script to be run, it must have permissions to run for the appropriate users. After you set the permissions, check that you actually set the permissions that you need. Once this is done, the script can be run just like any other command:

willy:~/scripts> chmod u+x script1.sh willy:~/scripts> ls -l script1.sh -rwxrw-r— 1 willy willy 456 Dec 24 17:11 script1.sh willy:~> script1.sh The script starts now. Hi willy! I will now fetch you a list of connected users: 3:38pm up 18 days, 5:37, 4 users, load average: 0.12, 0.22, 0.15 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT root tty2 — Sat 2pm 4:25m 0.24s 0.05s -bash willy:0 — Sat 2pm ? 0.00s ? — willy pts/3 — Sat 2pm 3:33m 36.39s 36.39s BitchX willy ir willy pts/2 — Sat 2pm 3:33m 0.13s 0.06s /usr/bin/screen I’m setting two variables now. This is a string: black And this is a number: 9 I’m giving you back your prompt now. willy:~/scripts> echo $COLOUR willy:~/scripts> echo $VALUE willy:~/scripts>

This is the most common way to execute a script. It is preferable to run scripts like this in a subshell. Variables, functions, and aliases created in this subshell are known only in that specific bash session in that subshell. When this shell is exited and the parent shell takes control, all settings are cleared and any changes that were made by the script to the state of that shell will be forgotten.

If you did not specify directory or (current directory) in the variable, you can activate the script as follows:

./script_name.sh

It is also possible to run a script inside an existing shell, but this is usually only done if you want special features, such as if you want to test whether a script works with another shell, or produce a trace for debugging purposes ( approx.— instead, specify the name of your script):

rbash script_name.sh sh script_name.sh bash -x script_name.sh

The specified command shell will be launched as a subshell of your current shell and will execute the script. This is done when you want the script to be run with specific parameters or under certain conditions that are not specified in the script itself.

If you don't want to start a new shell, but want to run the script in the current shell, use the command:

source script_name.sh

In this case, the script does not need execution rights. The commands are executed in the context of the current shell, so any changes that are made to your environment will remain visible when the script finishes executing:

willy:~/scripts> source script1.sh —output ommitted— willy:~/scripts> echo $VALUE 9 willy:~/scripts>

The command line and the incredible things you can do with it are the hallmark of UNIX and all its successors. And where there is a command line, there are scripts. And today... no, we will not learn to write scripts, we will look at the most useful of them, those that you can use daily to solve a wide range of problems, from weather reports and a web server in one line to a bot for Twitter in ten lines and a script to automatically launch any torrent client.

Let me make a reservation right away that I am not at all a follower of shamanism and in no way urge you to sit in a green and black console and type a bunch of letters in order to perform actions for which in the graphical interface you just need to hover the mouse over the desired element. However, I am convinced that for solving many problems the console and scripts are much better than the graphical interface and therefore cannot be neglected. Moreover, any DE allows you to create an icon for the script, so you don’t even need to open the console to run it.

Simple examples

So, without further ranting, let’s get straight to the examples:

$ curl ifconfig.co

This simple command will show you the external IP - ideal if you access the Network through a router. All it does is simply contact the ifconfig.co server, which returns the IP back in one line instead of a full web page.

And yes, this is not a script at all, it’s just a command, but to turn a command into a script, just put it in a text file and add the so-called shebang as the first line, that is, the symbols #!, followed by the name of the command interpreter:

$ chmod +x ~/bin/myip.sh

Now it can be called from the command line with the command myip.sh.

#!/bin/sh curl -4 wttr.in/Moscow

This script allows you to get a weather report for four days. The principle here is the same as in the case of ifconfig.co.

Weather report in the console #!/bin/sh dig +short txt $1.wp.dg.cx

And this way you can get a brief description of something on Wikipedia, using a DNS query instead of contacting a web server. By the way, it’s also very easy to create a web server via the command line:

#!/bin/sh while (nc -l 80< file.html >:) ; do: ; done

This script is based on the netcat (nc) utility, which is called the Swiss army knife of network operations. The script starts a loop that executes the nc command, which listens on port 80 and responds to the request with file.html, sending the passed request to nowhere (the symbol means noop, that is, an empty operation).

Using simple scripts and commands, you can easily listen to Internet radio:

#!/bin/sh mpv --volume=50 -playlist ~/16bit.fm_128.m3u

Naturally, the playlist in M3U format must be downloaded in advance from the radio station’s website. By the way, if you run MPlayer with the argument --input-ipc-server=/tmp/mpvsocket, it can be controlled by writing commands to a file. For example, adjust the volume:

Echo "volume +10" | socat - /tmp/mpvsocket

Create two scripts: one to start, the other to stop the radio (with the line killall mpv), hang them on your desktop and configure the DE hotkeys to control playback. Voila, you have a ready-made player for Internet radio, which you can launch by simply clicking on the icon on your desktop. And it will hardly consume memory or occupy the tray.

But let's take a break from network operations and return to local affairs.

#!/bin/sh tar -czf "../$(PWD##*/).tar.gz" .

This is one of my favorite scripts. It creates a tar.gz archive of the current directory. Particularly noteworthy here is the $(PWD##*/) construction, which takes the full path to the current directory (the $PWD variable) and removes the first part from it up to the last slash, thus leaving only the name of the directory itself. Next, the extension tar.gz is added to it. You can read more about such constructs in man bash.

#!/bin/sh while true; do inotifywait -r -e MODIFY DIRECTORY && YOUR_TEAM done

And this is a script that runs a command in response to changes in files in the directory. It can be used for many different purposes, such as automatically turning on the player when saving an MP3 file. Or simply display a notification on the desktop using notify-send as a command:

Notify-send "File changed"

Desktop

Since we're talking about the desktop, let's continue. Like the console, it can also be scripted. For example, here is a script that downloads random wallpapers published on the wallpaper reddit channel:

Continuation is available only to members

Option 1. Join the “site” community to read all materials on the site

Membership in the community within the specified period will give you access to ALL Hacker materials, increase your personal cumulative discount and allow you to accumulate a professional Xakep Score rating!

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, and full-fledged dialog scripts for working with them through the console.

 

It might be useful to read: