Hardware and software setup

A selection of shell scripts for all occasions. How to create your own script (script script) in Linux Ready-made scripts on shell linux

In the society of system administrators and ordinary Linux users, it is very often a famous practice to write Bash scripts in order to facilitate and simplify the implementation of specific goals in operating system linux. 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, painted the data, and so on, and then easily and simply write a single small command and all procedures are performed as needed.

It is possible to go even further and schedule the script-a to execute automatically. In case you are already a more experienced user, then most likely you do different things through the terminal quite often. This is just an example and there are a lot of such actions, even taking backup and uploading 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 new versions of packages.

This is a command shell where you have the ability to issue different commands that will start at high speed and fruitfully carry out different work. 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 just combine several commands that have some effect, and then execute them with the same command or even with 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 executable characteristic. And already 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- 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 the executable flag. Instead of this, start-of-file signatures and special flags are used. We have several different methods to do a script-a inclusion on a Linux OS. In Linux, the file extension is practically not used to determine its type at the system level. File managers can do this, but not always. The operating system considers executable only those files that have been assigned the executable characteristic. These are ordinary files that contain text.

Bash scripts Linux for dummies

A bash construct can be described in 7 commitments with a similar type: "shell invocation - bash script body - script end". Scripts are written with support for various text editors, they are stored as text computer data. But, to make it more comfortable, I store them together with the "*.sh" extension. But let's look at all this in terms 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 each time you are too lazy to enter these characteristics. 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-a, let's use the bash interpreter. The primary process for us is to call the interpreter. Open a text editor and write the code.

Let's add this operation, taking into account the introduced 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 as follows: text = "The balance of the user "user" was replenished with "cash" rubles at time"

The text argument varies depending on 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 put someone money, 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 with constantly entering the same values.

Create bash script in Linux OS

To write an ingenuous bash script, we need to perform such ordinary procedures. Create an empty file on the Linux command line (we call 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 will not need a lot of stress, but to outline a script (program), you will need to study various auxiliary literature. We will describe the most basic scripting, so let's get started, but if you don't 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 geditscript.sh

In my example, I will create a system update script, write it to this file. we will open the gedit text editor, I like vim more, but it will not be generally accepted for you, so I show it on the standard one.

sudo apt update;sudo apt full-upgrade;

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

chmod +x script.sh

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 superuser rights are required to run the script, then just write the sudo command before the script:

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

Of course, you can start the script by directly prescribing the interpreter: sh, bash and others:

bash script.shsh path/to/script.sh

As you can see, starting a sh script on linux is a fairly common task, even if you are not familiar with the terminal yet. There are really a lot of scripts and some of them you may need to execute. In this guide, we've covered some useful Linux bash scripts that you can use while using 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 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.

The Linux console is the tool that allows you to perform such manipulations that the command line in Windows does not allow you to do, the Linux console is the hallmark 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 on a daily basis to solve various kinds of tasks, 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 start any torrent client.

This material is not written for you to engage in shamanism, in no case do I urge you to sit in the console and type hundreds of characters to perform some actions that you can perform in the graphical interface just by hovering the mouse over the element you need. But there is one thing, but not always the graphical interface is the best solution, often for solving many problems the console and scripts cope with the task much better than applications with a graphical interface, and therefore you 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 run them without opening the console.

Let's start with simple examples

The command below will show you your external IP - this is ideal if you access the Network using a router. This command calls the ifconfig.co server, which returns the IP in a single line without any extra scribbling that you don't need.

Curl ifconfig.com

Yes, it's not a script, it's a small command, but if you want to turn this command into a script, you just need to put it in text file, in the end we get a small bash script:

#!/bin/bash curl ifconfig.co

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

Chmod +x ~/bin/yourip.sh

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

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

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

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

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

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

#!/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 to the 80th port and, in response to a request, gives file.html, sending the passed 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 one to start and the other one to stop the radio (in which we will write the line killall mpv), then hang it on the desktop together setting up the DE hotkeys to control playback. And you're done, you have a player with which you can listen to Internet radio.

We got carried away with 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. Particular attention should be paid to the $(PWD##*/) construct, which takes the entire path to the current directory ($PWD variable), then removes the first part up to the last slash, leaving only the directory name and adding the tar.gz extension to it. If you want to know more information on such constructs, you can read it by typing man bash in the console.

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

The script above runs a command in response to a change in files in a directory. You can use it for different purposes, as an example for automatic start 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 you will see an example of a script that loads random wallpapers posted on the wallpaper reddit channel:

#!/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 downloads the www.reddit.com/r/wallpaper page, then passes it to grep, which is already looking for links to imgur, and selects a random one with shuf, downloads it with wget and sets it as 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 plain 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 on click, and your wallpaper will change.

#!/bin/sh state=`synclient | grep Touchpad Off | 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 control the touchpads that are mostly produced by Synaptics, this is 90%, maybe even more. After starting the utility displays a lot of information, as well as the line TouchpadOff = 1 if it is enabled, and TouchpadOff = 2 if it is disabled. The script will read these values ​​and, depending on the state of the touchpad, will 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 picture using the webcam. The script uses an mpv video player that writes the first three frames taken by the camera into files jpeg format with the names 0000000.jpg, 00000002.jpg, 00000003.jpg, etc., then the third picture is renamed to photo.jpg, 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, then usually you will get a black picture. There are also incidents with positioning, the photo can be 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 only takes pictures 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, getting data from /dev/input/mouse0. If there is data, then the mouse was moved or one of its buttons was pressed. After that, mpv is used to create three snapshots, the third snapshot is given the name of the current date and the first two are deleted.

If you want to record a full video from a webcam, you can use a script like this as an example:

#!/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, 1800 bitrate and an MP3 audio file with 128 bitrate.

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

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

Import screenshot.png

If you run the command above, your mouse cursor icon 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 creating screenshots, and this combination will not eat 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 relies on the primary monitor being named LVDS and the external monitor named 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 an argument to the script off it disables the external monitor, argument on, in turn, includes it, placing it on the left side of the main (argument -left-of LVDS in the first team). After 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, commands xrandr-newmode... and xrandr -addmode ... are not needed as Xorg will get the monitor configuration and resolution using the EDID. Sometimes, however, this does not happen, and the configuration string specified after the argument -newmode, you have to generate it yourself using the cvt tool:

Cvt 1920 1080

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

Searching Google from the command line

Let's go back to network services. How to get the first 10 search results in 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=.+?&" | sed "s|/url?q=||; s| &||") echo -e "$(stream//\%/\x)"

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

YouTube service example:

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

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

A few examples of working with Twitter. Below you will see a full-fledged bot script that accepts a command as 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 console client ttytter, reading the last value of the direct message from the loop, after that it checks if this command has been executed, if not, it executes it and sends it to the specified user with the USER variable, trimming it 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 address bar browser, pass confirmation, agree, after you receive the authentication key, copy and paste it in the console in ttytter. Of course, before all this, it is desirable 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 feed 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, we look at 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 infinite loop and checks how much time in milliseconds has passed since the user performed the last action (xprintidle is used for this purpose). If 600,000 ms (ten minutes) have passed, 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 on the computer for ten minutes, after STARTCMD starts, in our case this is a command that starts all downloads in Transmission, if not, all downloads are suspended. Don't like the Transmission client? We use commands for Deluge, see below:

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

Conclusion

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, then you probably often perform various tasks through the terminal. 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 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 plain 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 pass the exact path to the program to be launched. And then it will pass your script to this program and execution will begin.

The simplest example of a script for a Bash shell:

!/bin/bash
echo "Hello world"

The echo utility prints 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, find out the interpreter and execute. 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 run:

chmod ugo+x script_file

Now we run our little first program:

./script_file

Everything is working. You already know how to write a small script for, say, an update. As you can see, the scripts contain the same commands that are executed in the terminal, they are very easy to write. But now we will complicate the task 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. All this can be done with the Bash shell. True, everything is much more complicated here. Let's start simple.

Variables in scripts

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

You may have encountered 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 fact, quotes are not always needed. The main principle of bash is preserved here - a space is a special character, a separator, 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 the way languages ​​do high level, like C++, you can assign both a number and 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 ways to merge strings, the role of quotes is also demonstrated here. If you need more sophisticated ways to handle strings, or arithmetic operations, this is not included in the capabilities of the shell, normal utilities are used for this.

Variables and command output

Variables would not be so useful if they could not store the result of executing utilities. The following syntax is used for this:

$(team )

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

Do you understand? Let's write a script where hello world and date will be displayed:

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

string=$string1$string2

Now you know enough about variables and you are ready to create a bash script, but there is more to come. Next, we will look at the parameters and control structures. Let me remind you that these are all regular bash commands, and you do not need to save them in a file, you can execute them immediately 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 of these parameters are available as variables named as numbers.

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

!/bin/bash
echo $1

Control constructs in scripts

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

In Bash, there is a command for checking 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 completion of the block of commands.

But since we are most often interested not in the return code of the command, but in comparing strings and numbers, the [[ command was introduced, which allows you to execute 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 already familiar operators<,>,=,!= and so on. If the expression is true, the command will return 0, if not - 1. You can test its behavior a bit in the terminal. The return code of the last command is stored in the $? variable:

Now, by 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 features, but it's too complicated to cover them in this article. Maybe I'll write about it later. For now, let's move on to cycles.

Loops in scripts

The advantage of programs is that we can specify in several 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, parsing the parameters and performing the necessary actions.

Let's first consider for loop. Here is its syntax:

for variable in list
do
team
done

Iterates over the entire list, and assigns the value from the list in turn to the variable, after each assignment, executes the commands located between do and done.

For example, let's iterate over five digits:

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

Or you can list all files in 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 while the condition command returns code 0, success. Consider the syntax:

while command condition
do
team
done

Consider 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 it increases the value of the variable by one.

I would like to note something else. Constructs such as while, for, if are designed to be written on multiple lines, and if you try to write them on one line, you will get an error. But nevertheless it is possible, for this, where there should be a line break, put a semicolon ";". For example, the previous loop could have been 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 bash terms and features, only the most basic. 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 which it is very convenient to display messages to the user and even ask him for information.

findings

Now you understand the basics of scripting in linux and you can write the script you need, for example, for Reserve copy. I tried to look at 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 do the following simple steps:

How it all works:

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

the second line creates the directory testdir

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

team 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 the script is launched, sequentially performs its work, performing certain actions.

If you run a chain of some identical commands (with constant parameters) on Linux every day, then it might make 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 you need 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. Input-output, redirection

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

almost like C printf "formatted output ten=%d string=%s float=%f hex_number=0x%X\n" 10 "string" 11.56 234 # example of reading keyboard input read A echo $A printf " you just entered word: %s\n" "$A" #redirection, pipelines, getting another program's output #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 the output to the screen of what is inside them (i.e. the program or script written inside such quotes is executed and the result printed by them on #standard output is the result of the operation "backquotes" #in this case, the result is the output of a pipeline from 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 stdout. #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 she received on std.in into lines of 10 characters long and prints it to stdout #head -1 prints 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 + \$B C=%d \n" "$C" # loop over i example 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 file existence # create file test1 touch test1 # check file existence test1 if [ -f test1 ] ; then echo "file test1 exists" fi # check if file test2 doesn't exist if ! [ -f test2 ] ; then echo "file test2 does not exist" fi # brief reference to other command options # -d filename directory exists # -f filename file exists # -L filename symlink exists # -r, -w, -x file is readable, writable or do # -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

Write a comment via:

How to write a simple bash script

How to run several commands sequentially in 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 performed sequentially. The shell waits for the next command, and returns to the command line prompt after the last command has been executed.

Simultaneous execution of several commands

To run multiple commands at once by putting 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 don't have to wait for the /root/ftpbackup.sh script to finish executing!

Using everything 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 it is simply necessary to know this language.
At its core, it's just a set of Linux commands, combined with the help of various constructs into smart 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.
At its core, the hash mark (#) is generally considered to be the beginning of a comment, but here, starting on the first line, it tells us that the bash interpreter should be used.

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 full place location.

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

Whenever we write scripts, we will be handling variables, redirecting input and output, working with pipes, and performing mathematical calculations.

Variables

To define a new variable, just say:

#!/bin/bash
F=Ivan
I=Ivanov
O=Ivanich
#Displayed 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 with ` `

#!/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 with the definition of the date the backup was created.

Redirecting input and output.

> Redirect to file with complete overwrite of file contents
>> Redirect to append to the file, to the end of existing content.
ls -al / > 123
And the command:
ls -al /home >> 123
List all files from the root and then add the contents of the Home directory after that
this redirection is called output redirection
Input Redirection - The content is redirected to the command.
sort< sort.txt
The sort command sorts alphabetically, as a result of which the randomly filled sort.txt file, after being redirected 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 for processing to the grep command, which displays only with 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 paging data

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

Mathematical calculations

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

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

Plutonit.ru - Administration, Linux setup and Windows 2009 - 2018

Database error: Table 'a111530_forumnew.rlf1_users' doesn't exist

Home -> MyLDP -> Electronic books for Linux OS

Creating and running a script

Write a script and choose a name for it

A shell script is a sequence of commands that you can use multiple times. This sequence is usually executed by typing the name of the script on the command line. Also, with cron, you can use scripts to automate tasks. Another use of scripts is the load and stop procedure UNIX systems when daemon and service operations 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 preventing mistakes that beginners often make, such as forgetting to close parentheses and semicolons.

Type UNIX commands in the new empty file just as you would type them on 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.

Choose a mnemonic name for your script that tells you what the script does. Make sure your script name doesn't conflict with existing teams. To avoid any confusion, script names often end with the .sh extension. However, there may be other scripts on your system with the same name you chose. Commands which, whereis and others, look for information about already existing programs and files in this name:

which -a script_name whereis script_name locate script_name ( approx.trans.

Writing scripts in Linux (learning by examples)

: replace with the name of your script).

Script script1.sh

In this example, we use the command echo, built into Bash, which will inform the user of what needs to be done before the output is produced. It is highly recommended that users be informed of what the script is doing so that users were not nervous in case it seemed to them that the script did nothing. We'll return to the topic of alerting users in Chapter 8, "Writing an Interactive Script."

Fig.2.1. Script script1.sh

Write the same script for yourself. It would be a good idea to create a directory where your scripts will be located. Add this directory to the contents 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, write and many other editors, see the documentation for your favorite editor.

Script execution

In order for a script to be able to run, it must have run rights for the appropriate users. After you set the permissions, check that you have indeed set the permissions 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. Hey 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 [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 $COLOUR willy:~/scripts> echo $VALUE willy:~/scripts>

This is the most the usual way execute the script. It is preferable to execute scripts like this in a subshell. Variables, functions, and aliases created in this subshell are known only to that particular bash session in that subshell. When this shell is exited and control is taken over by the parent shell, all settings are cleared and any changes that were made with the script in the shell's state will be forgotten.

If you didn't specify directories or (current directory) in the variable, you can activate the script like this:

./script_name.sh

It is also possible to execute the script inside an existing shell, but this is usually only done if you want to get special abilities, for example, if you want to check if the script works with another shell, or to issue a traceback for debugging purposes ( approx.trans.- instead specify the name of your script):

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

The specified shell will be launched as a subshell of your current shell and 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 execute the script in the current shell, use the command:

source script_name.sh

In this case, the script does not need execute permissions. Commands are executed in the context of the current shell, so any changes made to your environment will remain visible when the script has finished executing:

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

First of all, let's understand what is script and what it is for.

Script translated from English - scenario. We all watch films, many of us watch performances. To create a film/performance, screenwriters write scripts for them, on the basis of which the actors, scene by scene, perform their roles on the stage, from which the film/performance is formed. 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 a holistic work.

Similarly, scripts are written to execute a list of tasks that the user puts together (code) to make them easier and faster to run on the operating system. To write simple scripts, it is not necessary to have a programmer's education.

To begin with, let's create the most, that neither is, the simplest script-shell to update the system.

All actions I will carry out with the system ubuntu, but they apply 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 perform cos this script. These tools are installed in any distribution linux default.

So, open a text editor gedit and enter in it the first required characters under the name shebang.
shebang in programming, it is a sequence of two characters: a hash mark 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- it's usually Bourne shell or a compatible command line interpreter that passes "path/to/script" as the first parameter.
The first required line of the script will look like this:

# My First Ubuntu Update Script

The pound sign (#) at the very beginning of the line tells the interpreter/terminal that this line does not need to be read and executed. The line is needed in the code of this script so that the creator of the script 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 will be a lot of such lines. Such strings with a pound sign are called - commented out .

sudo apt update
sudo apt upgrade -y

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

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


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


In order for the created file/script to be executable, it needs to be given permission to do so. This can be done in two ways.

1. Run the following command in a terminal:

sudo chmod +x update.sh

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


To execute the created script, you need to open the 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, space-separated script name - update.sh and press the key Input:


Or in the terminal enter sh and drag from file manager the created file with the script (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 perform a system update:


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

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

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

Many of you most likely use system tuning sites like the ones I post after the next release. ubuntu - Ubuntu after installation or similar sites. Open one of these sites: then a text editor to create the script.
For example, I made the following blank.

In a text editor, enter the first required line:

# Ubuntu setup after installation
# System update

The following are the system update commands:

sudo apt update
sudo apt upgrade -y

Description line: Adding repositories:

# Adding repositories

And add the necessary repositories for further 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 may have your own repositories, I have an example), you need to update the system:

Line with description:

# Update the system after connecting the repositories

And the execution command:

sudo apt update

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

# Installing programs

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

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

Installing additional codecs

# Multimedia and codecs

sudo apt install ubuntu-restricted-extras -y

Shutdown about system failures

# Disable system crash reporting

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

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


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


We make the created script executable:

sudo chmod +x Setup\ Ubuntu.sh

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

Note. backslash in command Setup\Ubuntu.sh escapes a space in the filename for the terminal between two separate words.

After the script is executed, store it for the future, for a possible reinstallation of the system and reconfiguration, it is best on a separate section of the f / disk in the folder /home. If there is none, then in cloud service (Cloud storage data) 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.

Liked the article? Share with friends!
Was this article helpful?
Yes
Not
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thank you. Your message has been sent
Did you find an error in the text?
Select it, click Ctrl+Enter and we'll fix it!