Managing ubuntu through a script in windows. Execute a script when linux starts or shuts down. # Multimedia and codecs

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

How it all works:

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

second line mkdir testdir creates the testdir directory

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

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

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

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

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

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

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

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

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

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

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

# My first Ubuntu update Script

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

sudo apt update
sudo apt upgrade -y

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

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


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


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

1. Run the following command in the terminal:

sudo chmod +x update.sh

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


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


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


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


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

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

While you can continue to register manually as shown above, it is much better to set up some scripts to do this automatically for you.

A set of scripts automates the login process and starts PPP so that all you have to do (as root or as a member of the PPP group) is issue a single command to start your connection.

15.1 Connection scripts for authentication by user name/password

If your ISP doesn't require PAP/CHAP, these are the scripts you need!

If the ppp package is installed correctly, you should have two example files. For PPP 2.1.2 they are in /usr/sbin and for PPP 2.2 they are in /etc/ppp/scripts . They're called

for PPP-2. 1.2

and for PPP-2. 2

ppp-off ppp-on ppp-on-dialer

Now, if you are using PPP 2.1.2, I strongly urge you to remove the example files. There are potential problems with them (and don't tell me they work great), I've used them for a very long time (and even recommended them in the first version of this HOWTO)!

For PPP 2.1.2 user available BEST version template taken from the PPP 2.2 distribution. I suggest you copy and use these scripts instead of the old PPP-2.1.2 script.

15.2 ppp-on script

This is the first of a PAIR of scripts that actually start the connection.

#!/bin/sh # # Script to initiate a PPP connection. This is the first part of a couple of scripts. # These are not secret scripts, since the codes are visible with the ps command. # However, this is an example. # # These are the parameters. Change them as needed. TELEPHONE=555-1212 # Phone number connections ACCOUNT=george # Login username ("George Burns") PASSWORD=gracie # Password for this account (and "Gracie Allen") LOCAL_IP=0.0.0.0 # Local IP address, if known. Dynamic = 0.0.0.0 REMOTE_IP=0.0.0.0 # Remote IP address, if desired. Typically 0.0.0.0 NETMASK=255.255.255.0 # The corresponding netmask, if needed # # Export them so that they are available in the "ppp-on-dialer" export TELEPHONE ACCOUNT PASSWORD # # This is the location of the script that calls the phone and registers with # system. Please use an absolute filename as the connect # option does not use the $PATH variable. (If you do this, the "root" account will # be a security hole, so don't ask.) # DIALER_SCRIPT=/etc/ppp/ppp-on-dialer # # Initiating a connection # # exec /usr/sbin/pppd debug / dev/ttySx 38400 \ $LOCAL_IP:$REMOTE_IP \ connect $DIALER_SCRIPT

This is the ppp-on-dialer script:

#!/bin/sh # # This is the second part of the ppp-on script. It sets up the # desired connection. # /usr/sbin/chat -v \ TIMEOUT 3 \ ABORT "\nBUSY\r" \ ABORT "\nNO ANSWER\r" \ ABORT "\nRINGING\r\n\r\nRINGING\r" \ "" \rAT \ "OK-+++\c-OK" ATH0 \ TIMEOUT 30 \ OK ATDT$TELEPHONE \ CONNECT "" \ ogin:--ogin: $ACCOUNT \ assword: $PASSWORD

For PPP-2.2, the ppp-off script is something like this:

#!/bin/sh ############################################## ############################# # # Define the device to be interrupted. # if [ "$1" = "" ]; then DEVICE=ppp0 else DEVICE=$1 fi ######################################### ############################# # # If the pid file ppp0 is there, then the program works. Stop her. if [ -r /var/run/$DEVICE.pid ]; then kill -INT `cat /var/run/$DEVICE.pid` # # If kill fails, then there is no process running under this pid. # This could also mean that there is a foreign lock file. # You may want to remove it. if [! "$?" = "0" ]; then rm -f /var/run/$DEVICE.pid echo "ERROR: Removed stale pid file" exit 1 fi # # Great. Let pppd fix its own bug. echo "PPP link to $DEVICE terminated." exit 0 fi # # ppp process is not running for ppp0 echo "ERROR: PPP link is not active on $DEVICE" exit 1

15.3 Editing PPP launch scripts

Since new scripts come in two parts, we will edit them in turn.

ppp-on script

You will need to edit the script to insert YOUR username on your ISP, YOUR password on your ISP, your ISP phone number.

Each of the lines like TELEPHONE= are actually set shell variables that contain the information to the right of the = (excluding comments, of course). Edit each of these lines to match your ISP and connection.

Also, since you are setting the IP address (if you need it) in the /etc/ppp/options file, REMOVE the line that says

$LOCAL_IP:$REMOTE_IP \

Also, make sure that shell variable DIALER_SCRIPT points to the full path and name of the dialer script that you are actually going to use. So if you moved it or renamed the script, make sure you edit this line correctly in the ppp-on script!

ppp-on-dialer script

This is the second script that actually raises our ppp connection.

Please note: the chat script is usually a one-line script. Backslashes are used to space lines across multiple physical lines (for human readability) and avoid forming part of the script itself.

However, it is very useful to look at this in detail so that we understand what is actually (allegedly) happening!

15.4 What does the chat script mean...

Chat script - sequence of pairs expected stringsent string. In particular, please note that we ALWAYS wait for something before we send anything.

If we have to send something WITHOUT first receiving anything, we must use an empty wait string (denoted by "") and likewise for waiting for something without sending anything! Also, if the string consists of multiple words, (for example, NO CARRIER), you must put quotes around the string so that chat will treat it as one whole.

The chat line in our template:

Exec /usr/sbin/chat -v

When calling chat, the -v option tells chat to copy ALL I/O to the system log (usually /var/log/messages). Once you are confident that the chat script is working reliably, edit this line to remove the -v to avoid storing unnecessary information in your syslog

This sets the pause for receiving expected input to 3 seconds. You can increase this value to 5 or 10 seconds if you are using a slow modem!

ABORT "\nBUSY\r"

If the string BUSY is received, the operation aborts abnormally.

ABORT "\nNO ANSWER\r"

If the string NO ANSWER is received, the operation aborts abnormally.

ABORT "\nRINGING\r\n\r\nRINGING\r"

If (we repeat) the string RINGING is received, then the operation aborts abnormally.

It's because someone is on your phone line!

We don’t expect anything from the modem, and we’ll send a line to it

OK-+++\c-OK ATH0

This is a little more complex because it uses some of chat's error recovery capabilities.

What is says is... We are waiting OK if it is not received (because the modem is not in command mode), then send +++ (the standard line for Hayes-compatible modems, which returns the modem to command mode) and wait OK.

Then we send ATH0 (a line to terminate the modem connection). This allows your script to deal with your modem hanging during a call!

Let's set a time pause of 30 seconds for the remaining script commands. If you are having problems with the chat script breaking due to pauses, increase this value to 45 seconds or more

OK ATDT$TELEPHONE

We are waiting OK(the modem’s response to the ATH0 command) and dial the number we want to call

We wait for the CONNECT line (which our modem sends when the remote modem answers) and do not send anything in response

Ogin:--ogin: $ACCOUNT

Again, here we are putting in some bug fixes. We wait for the login prompt (...ogin:), but if we don't receive one after a pause, we send a carriage return and then look for the login prompt again. When the hint is received, we send the username (stored in the shell variable $ACCOUNT).

Assword: $PASSWORD

We wait for the password request and send our password (similarly stored in the shell variable).

This chat script has reasonable error correction capability. chat has significantly large quantity possibilities than shown here. For detailed information consult man chat (man 8 chat).

Running PPP on the server side of the connection

While the ppp-on-dialer script is great for servers that automatically start pppd on the server side as soon as you log in, some servers require you to explicitly command PPP to start on the server.

If you must issue a command to start PPP on the server, you must edit the ppp-on-dialer script.

AT THE END of the script (after the password line), add an additional expect-send string pair that looks for your login prompt (distinguishing characters that have special meaning in the Bourne shell: such as $ and [ or ] (open and closed square brackets).

Once the chat program has found the shell command line, it should issue the ppp start command required by your ISP's PPP server.

In my case, my PPP server uses the standard bash Linux prompt

and asks me to type

to start PPP on the server.

It would be good to take into account some errors here, so for example in my case I use

Hartr--hartr ppp

This means that if we do not receive a hint within a given pause, we send a carriage return and look for the hint again.

Once the hint is received, we send the line ppp .

Don't forget to add a \ to the end of the previous line so that chat thinks the entire chat script is one line!

Unfortunately, on some servers the set of hints changes frequently!

You may need to log in using minicom a few times to understand what's going on and find a stable expected line.

15.5 Chat script for PAP/CHAP connection

If your ISP uses PAP/CHAP then your chat script is much simpler.

Your entire chat script should do this: call a phone number, wait for a connection, and then let pppd handle the login!

#!/bin/sh # # This is part 2 of the ppp-on script. It will perform the connection # protocol for the desired connection. # exec /usr/sbin/chat -v \ TIMEOUT 3 \ ABORT "\nBUSY\r" \ ABORT "\nNO ANSWER\r" \ ABORT "\nRINGING\r\n\r\nRINGING\r" \ "" \ rAT \ "OK-+++\c-OK" ATH0 \ TIMEOUT 30 \ OK ATDT$TELEPHONE \ CONNECT "" \

15.6 Debugging pppd and the file option_file option

As we've already seen, you can enable debugging information with the -d option to pppd. The debug option is equivalent to it.

Since we are establishing a new connection with a new script, now check the debug option.

If you are low on disk space, pppd logs can quickly increase your syslog file and cause you a problem.

Once you are happy that everything is working correctly, you can remove this option.

If you named your ppp options file something other than /etc/ppp/options , or /etc/ppp/options.ttySx , specify the file name with the file option in pppd , for example

Exec /usr/sbin/pppd debug file options.myserver /dev/ttyS0 38400 \

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

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

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

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

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

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

# My first Ubuntu update Script

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

sudo apt update
sudo apt upgrade -y

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

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


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


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

1. Run the following command in the terminal:

sudo chmod +x update.sh

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


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


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


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


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

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

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

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

In a text editor, enter the first required line:

# Setting up Ubuntu after installation
# System update

The following are the system update commands:

sudo apt update
sudo apt upgrade -y

Description line: Adding repositories:

# Adding repositories

And add the necessary repositories for further installation of the software:

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

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

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

Description line:

# System update after connecting repositories

And the command to execute:

sudo apt update

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

# Installing programs

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

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

Installing additional codecs

# Multimedia and codecs

sudo apt install ubuntu-restricted-extras -y

Disabling system failures

# Disable system crash reporting

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

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


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


Let's make the created script executable:

sudo chmod +x Setup\Ubuntu.sh

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

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

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

A shell script is a sequence of commands that you can use repeatedly. Execution of this sequence is usually carried out by entering command line script name. Additionally, with cron you can use scripts to automate tasks. Another use of scripts is the boot and stop procedure UNIX systems, when init scripts define operations with daemons and services.

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

Dial UNIX commands in a new empty file just as if you had entered them on the command line. As discussed in the previous chapter (see the "Running a Command" section), commands can be shell functions, built-in commands, UNIX commands, or other scripts.

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

Which -a script_name whereis script_name locate script_name ( approx. : replace script_name 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 what needs to be done before the output is given. It is highly recommended that users be informed about what the script does so that users were not nervous if it seemed to them that the script was not doing anything. We'll return to the topic of notifying users in Chapter 8, "Writing an Interactive Script."


Fig.2.1. Script script1.sh

Write the same script for yourself. A good idea would be to create a ~/scripts directory where your scripts will be located. Add this directory to the content PATH variable:

Export PATH="$PATH:~/scripts"

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

Executing the script

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

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

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

If you did not specify the scripts or . (current directory), you can activate the script like this:

./script_name.sh

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

Rbash script_name.sh sh script_name.sh bash -x script_name.sh

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

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

Source script_name.sh

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

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