We write scripts in Linux (learning by example). Bash scripting Unix sh scripting

We write scripts in Linux (learning by example). Bash scripting Unix sh scripting

07.09.2021

For writing a simple bash script, we need to follow these 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 testdir directory

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

command touch on next line touch file1 file2 file3 creates three files

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

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

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

In the society of system administrators and ordinary Linux users, it is very often famous for the practice of writing Bash scripts in order to facilitate and simplify the implementation of specific goals in the Linux operating system. In this article we will look at writing scripts in Bash, look at the basic operators, and how they work, so to speak, bash scripts from scratch. Simply put, you once wrote the order of the activities that need to be done, painted the data, and so on, and then easily and simply write a single small command and all the procedures are performed as needed.

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

It is such a shell where you have the ability to produce different commands that will start at high speed and do different jobs fruitfully. Absolutely all the power of the linux OS is in using the terminal. Therefore, in order not to type the same commands several times, you can use scripts. This is very convenient, you just 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 executable only those files that have been assigned the executability characteristic. And already the interpreter says 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 executable flag. Instead of this, the signatures of the beginning of the file and special flags are used. We have several different methods to enable script-a in Linux. In Linux, the file extension is practically not used to determine its appearance at the system level. This can be done by file managers, and even then not always. The operating system considers executable only those files that have been assigned the executability characteristic. These are ordinary files that contain text.

Linux bash scripts for dummies

The bash construct can be described in 7 commitments with a similar type: "invoke the command interpreter - the body of the bash script - the end of the script". Scripts are written with support for various text editors, they are stored as textual computer data. But for convenience, I store them in conjunction with the "* .sh" extension. But let's take a look at all of this on a sample of a specific goal. There is a use that needs to be launched with a fairly large set of characteristics. You will often need to start, and every time you are lazy to enter these characteristics. To make it more definite, let's see how 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. As a primary process, you and I need to call the interpreter. Open up a text editor and write the 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 in the logs will be as follows: text = "The balance of the user" user "has been replenished with" cash "rubles at time"

The text argument varies due to the variables user, cash and time

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 amount of the payment. No long lines, no headaches of constantly entering the same values.

Create bash script in Linux OS

To compose an artless script in bash, we need to perform such ordinary procedures. Let's create an empty file on the Linux command line (we name it firstscript for the sample) and open it for editing in your favorite text editor (vi / vim, nano, gedit, and so on). To develop a script, you do not need a lot of stress, but in order to sketch a script (program), you will need to study various auxiliary literature. We will describe the most basic of scripting, so we start, but if you do not know what a terminal is and how to use it, then you are here. 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, write it to this file. we will open the gedit text editor, I love vim more, but you will not have it most generally accepted, so I show it in the standard one.

sudo apt update; sudo apt full-upgrade;

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

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. / In front of the script file name:

Sometimes superuser rights are required to run the script, then just before the script we write the sudo command:

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

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

bash script.shsh path / to / script.sh

As you can see, starting the sh script on linux is a fairly common task, even if you are not familiar with the terminal yet. There are a lot of scripts out there and some of them you may need to run. In this tutorial, we have covered useful Linux bash scripts that you can use when using Linux. In this article, we looked at useful linux bash scripts that you can use while working with the system. Certain of them consist of several lines, a few are placed on one line. There are both minor snippets that you can use in your scripts, and full-fledged dialog scripts to work with them through the console.

First of all, let's take a look at what is script and what is it for.

Script translated from English - scenario... We all watch films, many of us watch performances. To create a film / play, the scriptwriters write scripts for them, on the basis of which the actors, scene by scene, perform their roles on stage, which makes up the film / play. The work on creating the script is quite painstaking, where you need to take into account everything to the smallest detail, so that in the end the artists can fulfill the scriptwriter's plan, and the viewer sees the whole work.

Likewise, scripts are written to perform a list of tasks that the user puts together (code) to make them easier and faster in the operating system. It is not necessary to have a programmer education to write simple scripts.

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

I will carry out all actions with the system Ubuntu but they are applicable to other systems as well 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 on any distribution Linux default.

So, open a text editor Gedit and enter the first required characters in it under the name shebang.
shebang in programming, it 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 upgrade 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 script creator himself knows what he is going to execute on this segment / scene in the code, so as not to get confused in the future when there are a lot of 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, pressing a key Input. y- abbreviated from English yes, i.e. Yes.

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


It remains to save the created file / script and give it Name with a required 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. This can be done in two ways.

1. Run the following command in terminal:

sudo chmod + x update.sh

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


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


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


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


Now at any time you can make a system update created by your own script.

Yes, someone may 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 all right. But this is an example of creating the simplest script to show that "it is not gods who burn pots" 😃.

Having learned how to write and use the simplest scripts, you can create a script to configure the system so that in the event of a system reinstallation, you can use the created script without having to search the network for sites with similar settings every time.

Many of you, most likely, use sites to configure the system, 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 template.

In a text editor, enter the first required line:

# Setting up Ubuntu after installation
# System update

The following are the commands to update the system:

sudo apt update
sudo apt upgrade -y

Description line: Add repositories:

# Adding repositories

And add the necessary repositories for further software installation:

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 are added (again, you can have your own repositories, I have an example), you need to update the system:

Description line:

# Updating the system after connecting the repositories

And the command to execute:

sudo apt update

Now that the repositories have been added and the system has been updated, it is the turn to install the programs:

# Installing programs

To install programs, just enter the command once sudo apt install, and then add as many programs as you like to this line through a space, the main thing is that they are correctly composed. If a program consists of several words, its command must be monolithic, i.e. all words in it must be entered with 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

Disable System Crash

# 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:


It is necessary to save it (press the button Save) and give Name with extension .sh... I named him Setup \ Ubuntu.sh(you can name it differently, but with the extension .sh):


We 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, space bar and drag the created file into the terminal, as explained earlier in the simplest script and press the key Input to execute it.

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

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

For writing a simple bash script, we need to follow these 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

command touch 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 appeared.

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

If you daily run a chain of any identical commands (with constant parameters) in Linux, then it may make sense for you to write the same simple bash script which will save you 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 run, you need to change the access rights to it by 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 a # # To display a message, use the ECHO command echo "hello, world" # this is an example of formatted output ...

almost like C printf "formatted output ten =% d string =% s float =% f hexadecimal = 0x% X \ n" 10 "string" 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 password from 10 letters PASSWORD1 =` cat / dev / urandom | tr -d -c ‘a-zA-Z0-9’ | fold -w 10 | head -1` echo Password = $ PASSWORD1 # quotes like "give the result of displaying what is inside them (i.e., # a program or script written inside such quotes is executed and the result they print to # standard output is the result of the operation "backticks" # in this case, the result is pipe output from multiple programs.

Interesting bash scripts for Linux terminal lovers

# operation | denotes a 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 standard output #tr performs translation, i.e. replaces some bytes with others (this is necessary to avoid the appearance of non-readable characters in the password) #fold splits what came to the standard input into lines 10 characters long and outputs it to the standard output #head -1 outputs the first line what came to her 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 the number of times

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

3.Different kinds of checks

#! / bin / bash # example of checking the existence of a file # creating a file test1 touch test1 # checking the existence of a file test1 if [-f test1]; then echo "file test1 exists" fi # check if test2 does not exist if! [-f test2]; then echo "file test2 does not exist" fi # brief help on other command options # -d filename directory exists # -f filename file exists # -L filename symlink exists # -r, -w, -x file is read / write or # -s filename file exists and has non-zero length # f1 -nt f2 f1 newer than f2 # f1 -ot f2 f1 older than f2

Tags: bash, freebsd, shell

Write a comment via:

How to write a simple bash script

How to run several commands in succession or all at once? If you need to run several commands, then the symbol “ ; "Called a metacharacter. The syntax is as follows command1; command2; command3

Commands separated by " ; »Are executed sequentially. Shell waits for the next command, and returns to the command prompt after the last command has been executed.

Simultaneous execution of several commands

To run multiple commands in one go, by putting an ampersand "&" at the end of the command. For example, consider the beginning of a backup script:

# /root/ftpbackup.sh &

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

Using everything together

You can have thousands of * .bak files. But you just need to list the categories you need, and put everything in / tmp / list:

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

A 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 collection of Linux commands combined using different constructs into 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.
At its core, the hash (#) is generally considered the start of a comment, but here, starting on the first line, it tells us to use the bash interpreter.

1) It is necessary to give the rights to execute

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 refer to it simply by name, and not by its full location.

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

Whenever we write scripts, we will deal with 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
# Outputted with:
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 the script, for example, a backup

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

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

Redirecting input and output.

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

Another useful thing to know is the transfer of 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 transferred for processing to the grep command, which outputs only with Blocked, but since there are a lot of messages with this status, it is necessary to transfer it to the more command
3) more - needed to view the data page by page

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

Math calculations

Linux math is easiest to do with the bc command
In this case, it is not necessary to set the number of digits after the 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 -> Linux eBooks

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 over and over again. The execution of this sequence, as a rule, is carried out by entering the name of the script on the command line. Also, with cron, you can use scripts to automate tasks. Another use for scripts is to boot and shutdown a UNIX system, where init scripts define operations with daemons and services.

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

Type UNIX commands in a new, empty file, just as you would typing them on the command line. As discussed in the previous chapter (see “Executing a Command”), commands can be shell functions, built-in commands, UNIX commands, or other scripts.

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

which -a script_name whereis script_name locate script_name ( approx.

Writing scripts in Linux (learning by example)

: replace with the name of your script).

Script script1.sh

In this example, we use the command echo, built into Bash, which informs the user of what needs to be done before outputting the output. It is highly recommended that you inform users of what the script does so that users don't get nervous if it seems to them that the script does nothing... We'll return to the topic of notifying users in Chapter 8, Writing an Interactive Script.

Figure 2.1. Script script1.sh

Write the same script for yourself. It would be a good idea to create a directory for your scripts. Add this directory to the content of the variable:

export PATH = "$ PATH: ~ / scripts"

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

Executing a script

In order for the script to be run, it must have run rights for the appropriate users. After you set the permissions, check that you have actually set the permissions you want. When 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:38 pm up 18 days, 5:37, 4 users, load average: 0.12, 0.22, 0.15 USER TTY FROM [email protected] 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 $ COLOR 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 this particular bash session in this subshell. When this shell is exited and control is taken over by the parent shell, all settings are cleared and any changes made by the script in the state of that shell are forgotten.

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

./script_name.sh

You can also execute the script inside an existing shell, but this is usually only done if you want accessibility, for example, if you want to check if the script works with another shell, or to issue a trace for debugging purposes ( approx.- specify the name of your script instead):

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

The specified command shell will start as a subshell of your current shell and execute the script. This is done when you want the script to 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 command shell, but want to execute the script in the current shell, use the command:

source script_name.sh

In this case, the script does not need execute permission. 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 Linux console is the tool that allows you to perform such manipulations that the command line in Windows does not allow, the Linux console is the calling card of UNIX. Today the material is not about how to write scripts, no, I will not teach you how, what and why. We will look at a small selection of useful scripts that you can use every day to solve various problems, for example, look at the weather for several days in advance, scripts for a web server in one line, writing a bot for Twitter and a script to automatically launch any torrent client.

This material is not written so that you are engaged in shamanism, in no case I urge you to sit in the console and type hundreds of characters in order to perform some actions that you can perform in the graphical interface only by hovering the mouse over the element you need. But there is one thing, but the graphical interface is not always the best solution, often for solving many tasks, the console and scripts cope with the task much better than applications with a graphical interface, and therefore one should not forget about scripts, since they solve a lot of routine work better than graphical ones. tools. It is also worth adding that any DE allows you to create an icon for your scripts, by clicking on which, you can easily launch them without opening the console.

Let's start with simple examples

The command below will show you your external IP - ideal if you access the Network using a router. This command accesses the ifconfig.co server, which returns the IP in one line without the hassle of writing.

Curl ifconfig.co

Yes, this is not a script, it is a small command, but if you want to turn this command into a script, you just need to put it in a text file, as a result we will get a small bash script:

#! / bin / bash curl ifconfig.co

We save the script to the ~ / bin directory and grant execution permissions:

Chmod + x ~ / bin / yourip.sh

Almost done, you can run the script from the command line using the yourip.sh command.

We finished with the ip, let's see the weather from the console.

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

This script allows you to get a weather summary for four days, in this case the weather for the city of Kiev.

#! / bin / sh dig + short txt $ 1.wp.dg.cx

Above you see an example of how you can get a short description of something on Wikipedia, in our case we use a DNS query instead of accessing a web server. It is also very easy to create a web server via the console:

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

The script above is based on the netcat (nc) utility, often called the Swiss army knife, as it allows you to do a lot of tricks for network operations. The script is simple, it starts a loop that executes the nc command, it is already listening on the 80th port and in response to the request gives file.html, sending the transmitted request to nowhere (the symbol means noop, that is, an empty operation).

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

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

Of course, before that you need to download the radio playlist in M3U format from the radio station's website. If you start MPlayer using 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

We create two scripts: the first for starting, and the other for stopping the radio (in which we will write the killall mpv line), then hang it on the desktop by jointly configuring DE hotkeys to control playback. And you're done, you have a player with which you can play Internet radio.

Carried away by network operations, let's move on to local ones.

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

This script creates a tar.gz archive for the current directory. Special attention should be paid to the construction $ (PWD ## * /), which takes the entire path to the current directory (variable $ PWD), then removes the first part to the last slash, as a result, only the directory name remains and the tar.gz extension is added to it. If you would like to know more information about such constructs, you can read it by running man bash in the console.

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

The script above runs the command in response to file changes in the directory. You can use it for different purposes, as an example to automatically turn on the player when saving MP3. Or, as an example, display a notification on the desktop using the notify-send command:

Notify-send "File changed"

Desktop

Below is an example of a script that loads a random wallpaper that is posted on the wallpaper reddit:

#! / bin / bash wget -O - http://www.reddit.com/r/wallpaper | \ grep -Eo "http://i.imgur.com [^ &] + jpg" | \ shuf -n 1 | \ xargs wget -O background.jpg feh --bg-fill background.jpg

Everything works quite simply. Using the wget utility, the script loads the www.reddit.com/r/wallpaper page, then passes it to grep, which is already looking for links to imgur, and picks a random one with shuf, loads it using wget and sets it as the wallpaper for your desktop. using the feh command (this is a miniature image viewer that needs to be installed first). You can add this script to a regular text file as I described above, save it in sh format, make it executable, add an icon to it and run it from the desktop by clicking and your wallpaper will change.

#! / bin / sh state = `synclient | grep TouchpadOff | cut -d "=" -f 2` if [$ state = "1"]; then synclient TouchpadOff = 0 else synclient TouchpadOff = 1 fi

The script above is used to enable and disable your laptop's touchpad: enable if disabled, and vice versa. For correct operation, it uses the synclient utility, which allows you to manage touchpads that are mostly produced by Synaptics, this is 90% possibly even more. After starting the utility displays a lot of information, as well as the line TouchpadOff = 1, if enabled, and TouchpadOff = 2, if disabled. The script will read these values ​​and, depending on the state of the touchpad, enable or disable it.

! # / bin / bash mpv tv: // -frames 3 -vo jpeg mv 00000003.jpg photo.jpg rm -f 0000 * .jpg

Using the script above, you can take a snapshot using your webcam. The script uses a video player mpv that writes the first three frames taken by the camera to JPEG files with the names 0000000.jpg, 00000002.jpg, 00000003.jpg, etc., after which the third image is renamed to the photo.jpg file, and the rest are deleted. What are the three shots used for? They are only needed so that your camera has time to initialize, if you use the first two shots, you usually get a black shot. There are also incidents with positioning, the photo can be turned upside down; to avoid this, mpv must be run with the -vf flip flag:

Mpv tv: // -frames 3 -vf flip -vo jpeg

You can use the same command to create a security camera that will take pictures only when the user touches the mouse:

#! / bin / bash while true; do sudo cat / dev / input / mouse0 | read -n1 mpv tv: // -frames 3 -vo jpeg mv 00000003.jpg `date +% F-% H-% M`.jpg rm -f 0000 * .jpg sleep 10 done

The script above uses an infinite loop to receive data from the / dev / input / mouse0 device. If there is data, then the mouse was moved or one of its buttons was pressed. Then mpv is used to create three snapshots, the third snapshot is named the current date and the first two are deleted.

If you want to record a full-fledged video from a webcam, as an example, you can use a similar script:

#! / bin / bash mencoder tv: // -tv driver = v4l2: width = 800: height = 600: device = / dev / video0: fps = 30: outfmt = yuy2: forceaudio: alsa: adevice = hw.2, 0 -ovc lavc -lavcopts vcodec = mpeg4: vbitrate = 1800 -ffourcc xvid -oac mp3lame -lameopts cbr = 128 -o video.avi

As a result, you will get a file called video.avi in ​​MPEG4 format with 1800 bit rate and an audio file in MP3 format with 128 bit rate.

#! / bin / bash ffmpeg -f x11grab -r 25 -s 1366x768 -i: 0.0 screencast.mpg

Using the script above, you can record a full screencast. 1366 × 768 is the desktop resolution, you can customize it for yourself. To take a screenshot of a separate window, you can use the import command:

Import screenshot.png

If you run the command above, the icon of your mouse cursor will change to a cross, using which you can select an area of ​​the screen as you do when taking screenshots using third-party applications or extensions. If you hang this command on one of the hotkeys, you will get an almost perfect system for taking screenshots, and this combination will not eat up your RAM, which makes it a huge plus.

You can also set up an external monitor using the console:

#! / bin / sh if [-z "$ 1"]; then exit fi if [$ 1 == "off"]; then xrandr --output VGA-0 --off xrandr -s 0 else if [$ 1 == "on"]; then xrandr --output LVDS --auto --primary --output VGA-0 --auto --left-of LVDS xrandr --newmode "1920x1080" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync + vsync xrandr - addmode VGA-0 1920x1080 xrandr --output VGA-0 --mode 1920x1080 fi xrandr --dpi 96

This script is based on the fact that the main monitor is named LVDS and the external one is VGA-0. This is the standard situation for all laptops; if you are not sure, you can check by running the xrandr command: when passing the argument to the script off it turns off the external monitor, the argument is on, in turn, turns it on, positioning it to the left of the main (argument -left-of LVDS in the first team). Then the script creates a new configuration for the monitor with a resolution of 1920 x 1080 and activates it. And in the end, the script sets the default DPI value - because when you connect a monitor with a different resolution, it often crashes.

In most cases, the commands xrandr -newmode ... and xrandr -addmode ... not needed as Xorg will get the monitor configuration and resolution using EDID. Sometimes, however, this does not happen, and the configuration line after the argument -newmode, you have to generate it yourself using the cvt tool:

Cvt 1920 1080

Using the cvt tool, you can generate non-standard resolutions that are not supported by the default monitor.

Searching Google from the command line

Let's go back to network services again. How to get the first 10 search results on Google? See the script below:

#! / bin / bash Q = "" URL = "https://www.google.de/search?tbs=li:1&q=" AGENT = "Mozilla / 4.0" stream = $ (curl -A "$ AGENT" -skLm 10 "$ (GOOG_URL) $ (Q // \ / +)" | grep -oP "\ / url \? q =. +? & amp" | sed "s | / url? q = ||; s | & amp || ") echo -e" $ (stream // \% / \ x) "

This script sends a request to Google using curl, replaces the spaces in the search bar with pluses. Then links pop up in the response HTML

Example with YouTube service:

#! / bin / bash mpv -fs -quiet `youtube-dl -g" $ 1 "`

The script from the example above plays the video with the specified ID in the argument using the mpv player. You need to install youtube-dl in advance.

Here are some examples of working with Twitter. Below you will see a script of a full-fledged bot that accepts a command at the input, executes it using the command interpreter and sends the result to the specified user.

#! / bin / bash USER = "Your Nickname" while true; do CMD = `echo" / dma +1 "| ttytter -script | sed "s / \ [. * \] \ //" if [$ CMD! = $ OLD_CMD]; then REPL = `$ CMD` echo" / dm $ USER $ (REPL: 0: 140) "| ttytter -script CMD = $ OLD_COMD fi sleep 60 done

The script uses the ttytter console client, reading the last value of the direct message from the loop, then it checks whether this command has been executed, if not, executes it and sends it to the specified user with the USER variable trimming to 140 characters.

For everything to work, you need to install the ttytter utility, run it, then copy the generated link from the console and paste it into the browser address bar, go through confirmation, agree, then get the authentication key, copy and paste it into the console in the ttytter. Of course, before all this, it is advisable to add a separate user and log in under his account.

You can use Twitter not only to create a bot, but also to monitor the machine. The script below sends a message to the tape with information about the state of the machine (hostname, uptime, load, free memory and CPU load):

#! / bin / bash HOST = `hostname -s` UP =` uptime | cut -d "" -f4,5 | cut -d "," -f1` LOAD = `uptime | cut -d ":" -f5,6` MEM = `ps aux | awk "(sum + = $ 4); END (print sum)" `CPU =` ps aux | awk "(sum + = $ 3); END (print sum)" `tweet =" Host: $ (HOST), uptime: $ (UP), cpu: $ (CPU)%, memory: $ (MEM)%, loadavg $ (LOAD) "if [$ (echo" $ (tweet) "| wc -c) -gt 140]; then echo "FATAL: The tweet is longer than 140 characters!" exit 1 fi echo $ tweet | ttytter -script

Finally, see the script below, this script is used to start and stop the torrent client while your PC is idle:

#! / bin / bash IDLE = 600000 STOPCMD = "transmission-remote -S" STARTCMD = "transmission-remote -s" STOPPED = "yes" while true; do if [`xprintidle` -gt $ IDLE]; then if [$ STOPPED = "yes"]; then $ STARTCMD STOPPED = "no" fi else if [$ STOPPED = "no"]; then $ STOPCMD STOPPED = "yes" fi fi sleep 60 done

Every minute the script goes into an endless loop and checks how much time in milliseconds has passed since the moment when the user performed the last actions (xprintidle is used for this purpose). If 600,000 ms (ten minutes) has elapsed, the script executes the command specified in the STARTCMD variable. Otherwise, the STOPCMD command is executed, but only if STARTCMD was executed before it. In simple terms, you do nothing at the computer for ten minutes, then STARTCMD starts, in our case, this is the command that starts all downloads in Transmission, if not, all downloads are paused. Don't like the Transmission client? We use the commands for Deluge, see below:

STOPCMD = "deluge-console pause \ *" STARTCMD = "deluge-console resume \ *"

Output

© 2021 hecc.ru - Computer technology news