Computer literacy, assistance and repair

Starting and stopping the pCloud client on Linux on a schedule using bash scripts. Process automation

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 the PPP 2.1.2 user there is a BETTER version of the 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 # Connection telephone number 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 the DIALER_SCRIPT shell variable points to the full path and name of the dialer script 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 more features than shown here. For details, 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 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, 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: , then a text editor to create a script.
For example, I made the following blank.

In a text editor, enter the first required line:

# Setting up Ubuntu after installation
# System update

The following are the system update commands:

sudo apt update
sudo apt upgrade -y

Description line: Adding repositories:

# Adding repositories

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

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

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

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

Description line:

# System update after connecting repositories

And the command to execute:

sudo apt update

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

# Installing programs

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

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

Installing additional codecs

# Multimedia and codecs

sudo apt install ubuntu-restricted-extras -y

Disabling system failures

# Disable system crash reporting

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

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


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


Let's make the created script executable:

sudo chmod +x Setup\Ubuntu.sh

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

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

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

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 add as many programs as you like into this line, separated by a space, the main thing is that they are composed correctly. If a program consists of several words, its command must be monolithic, i.e. all words in it must be entered through a dash, for example: unity-tweak-tool:

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

Installing additional codecs

# Multimedia and codecs

sudo apt install ubuntu-restricted-extras -y

Disabling system failures

# Disable system crash reporting

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

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


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


Let's make the created script executable:

sudo chmod +x Setup\Ubuntu.sh

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

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

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

Today we'll talk about bash scripts. These are command line scripts written for the bash shell. There are other shells, for example - zsh, tcsh, ksh, but we will focus on bash. This material is intended for everyone, the only condition is the ability to work on the Linux command line.



Command line scripts are collections of the same commands that can be entered from the keyboard, collected into files and united by some common purpose. In this case, the results of the teams’ work can either be of independent value or serve as input data for other teams. Scripts are a powerful way to automate frequently performed actions.

So, if we talk about command line, it allows you to execute multiple commands at once by entering them separated by semicolons:

Pwd; whoami
In fact, if you tried this in your terminal, your first bash script involving two commands has already been written. It works like this. First, the pwd command displays information about the current working directory, then the whoami command displays information about the user under which you are logged in.

Using this approach, you can combine as many commands as you like on one line, the only limit is the maximum number of arguments that can be passed to the program. You can define this limit using the following command:

Getconf ARG_MAX
The command line is a great tool, but you have to enter commands into it every time you need them. What if we wrote a set of commands into a file and simply called that file to execute them? In fact, the file we are talking about is called a command line script.

How bash scripts work

Create an empty file using the touch command. Its first line needs to indicate which shell we are going to use. We are interested in bash , so the first line of the file will be like this:

#!/bin/bash
Other lines in this file use the hash symbol to indicate comments that the shell does not process. However, the first line is a special case, there is a hash followed by Exclamation point(this sequence is called a shebang) and the path to bash indicate to the system that the script was created specifically for bash.

Shell commands are separated by a line feed, comments are separated by a hash sign. This is what it looks like:

#!/bin/bash # This is a comment pwd whoami
Here, just like on the command line, you can write commands on one line, separated by semicolons. However, if you write the commands on different lines, the file is easier to read. In any case, the shell will process them.

Setting script file permissions

Save the file and name it myscript and you're almost done creating your bash script. Now all that remains is to make this file executable, otherwise, if you try to run it, you will encounter a Permission denied error.


Attempting to run a script file with incorrectly configured permissions

Let's make the file executable:

Chmod +x ./myscript
Now let's try to execute it:

./myscript
After setting the permissions everything works as it should.


Successfully running bash script

Message output

To output text to the Linux console, use the echo command. Let's use the knowledge of this fact and edit our script, adding explanations to the data that is output by the commands already in it:

#!/bin/bash # our comment is here echo "The current directory is:" pwd echo "The user logged in is:" whoami
This is what happens after running the updated script.


Outputting messages from a script

Now we can display explanatory notes using the echo command. If you don't know how to edit a file using Linux tools, or haven't encountered the echo command before, take a look at this resource.

Using Variables

Variables allow you to store information in a script file, such as the results of commands, for use by other commands.

There is nothing wrong with executing individual commands without storing their results, but this approach is quite limited in its capabilities.

There are two types of variables that can be used in bash scripts:

  • Environment Variables
  • User Variables

Environment Variables

Sometimes shell commands need to work with some system data. Here's an example of how to display the current user's home directory:

#!/bin/bash # display user home echo "Home for the current user is: $HOME"
Please note that we can use the $HOME system variable in double quotes, this will not prevent the system from recognizing it. This is what you get if you run the above scenario.


Using an environment variable in a script

What if you need to display a dollar sign on the screen? Let's try this:

Echo "I have $1 in my pocket"
The system will detect a dollar sign in a quoted string and assume that we have referenced a variable. The script will try to display the value of the undefined variable $1. This is not what we need. What to do?

In this situation, using the escape character, a backslash, before the dollar sign will help:

Echo "I have \$1 in my pocket"
The script will now output exactly what is expected.


Using an escape sequence to print a dollar sign

User Variables

In addition to environment variables, bash scripts allow you to define and use your own variables in the script. Such variables hold a value until the script completes execution.

As with system variables, user variables can be accessed using the dollar sign:
TNW-CUS-FMP - promo code for a 10% discount on our services, available for activation within 7 days
#!/bin/bash # testing variables grade=5 person="Adam" echo "$person is a good boy, he is in grade $grade"
This is what happens after running such a script.


Custom Variables in a Script

Command Substitution

One of the most useful features of bash scripts is the ability to extract information from command output and assign it to variables, allowing that information to be used anywhere in the script file.

There are two ways to do this.

  • Using the backtick "`"
  • Using the $() construct
When using the first approach, be careful not to include a single quotation mark in place of the backtick. The command must be enclosed in two such icons:

Mydir=`pwd`
In the second approach, the same thing is written like this:

Mydir=$(pwd)
And the script might end up looking like this:

#!/bin/bash mydir=$(pwd) echo $mydir
During its operation, the output of the pwd command will be stored in the mydir variable, the contents of which, using the echo command, will be sent to the console.


A script that saves the results of a command in a variable

Mathematical operations

To perform mathematical operations in a script file, you can use a construct like $((a+b)) :

#!/bin/bash var1=$((5 + 5)) echo $var1 var2=$(($var1 * 2)) echo $var2


Mathematical Operations in a Script

if-then control construct

In some scenarios, you need to control the flow of command execution. For example, if a certain value is greater than five, you need to perform one action, otherwise, another. This is applicable in many situations, and here the if-then control construct will help us. In its simplest form it looks like this:

If command then fi commands
Here's a working example:

#!/bin/bash if pwd then echo "It works" fi
IN in this case, if the pwd command completes successfully, the text “it works” will be printed to the console.

Let's use the knowledge we have and write a more complex script. Let's say we need to find a certain user in /etc/passwd, and if we were able to find him, report that he exists.

#!/bin/bash user=likegeeks if grep $user /etc/passwd then echo "The user $user Exists" fi
This is what happens after running this script.


Search for a user

Here we have used the grep command to search for the user in the /etc/passwd file. If the grep command is unfamiliar to you, its description can be found.

In this example, if the user is found, the script will display a corresponding message. What if the user could not be found? In this case, the script will simply complete execution without telling us anything. We'd like him to tell us about this too, so we'll improve the code.

if-then-else control construct

In order for the program to be able to report both the results of a successful search and failure, we will use the if-then-else construct. Here's how it works:

If command then commands else commands fi
If the first command returns zero, which means it was executed successfully, the condition will be true and execution will not proceed along the else branch. Otherwise, if something other than zero is returned, which would indicate failure, or a false result, the commands after else will be executed.

Let's write the following script:

#!/bin/bash user=anotherUser if grep $user /etc/passwd then echo "The user $user Exists" else echo "The user $user doesn’t exist" fi
Its execution went along the else branch.


Running a script with an if-then-else construct

Well, let's move on and ask ourselves about more complex conditions. What if you need to check not one condition, but several? For example, if the desired user is found, one message should be displayed, if some other condition is met, another message should be displayed, and so on. In such a situation, nested conditions will help us. It looks like this:

If command1 then commands elif command2 then commands fi
If the first command returns zero, indicating success, the commands in the first then block will be executed, otherwise, if the first condition is false, and if the second command returns zero, the second block of code will be executed.

#!/bin/bash user=anotherUser if grep $user /etc/passwd then echo "The user $user Exists" elif ls /home then echo "The user doesn’t exist but anyway there is a directory under /home" fi
In such a script, you can, for example, create a new user using the useradd command if the search does not produce results, or do something else useful.

Comparison of numbers

In scripts you can compare numeric values. Below is a list of relevant commands.
n1 -eq n2 Returns true if n1 equals n2 .
n1 -ge n2 Returns true if n1 is greater than or equal to n2 .
n1 -gt n2 Returns true if n1 is greater than n2 .
n1 -le n2 Returns true if n1 is less than or equal to n2 .
n1 -lt n2 Returns true if n1 is less than n2 .
n1 -ne n2 Returns true if n1 is not equal to n2 .

As an example, let's try one of the comparison operators. Note that the expression is enclosed in square brackets.

#!/bin/bash val1=6 if [ $val1 -gt 5 ] then echo "The test value $val1 is greater than 5" else echo "The test value $val1 is not greater than 5" fi
This is what this command will output.


Comparison of numbers in scripts

The value of the val1 variable is greater than 5, as a result the then branch of the comparison operator is executed and a corresponding message is displayed in the console.

String comparison

Scripts can also compare string values. Comparison operators look quite simple, but string comparison operations have certain features, which we will touch on below. Here is a list of operators.
str1 = str2 Tests strings for equality, returning true if the strings are identical.
s tr1 != str2 Returns true if the strings are not identical.
str1< str2 Возвращает истину, если str1 меньше, чем str2 .
str1 > str2 Returns true if str1 is greater than str2 .
-n str1 Returns true if the length of str1 is greater than zero.
-z str1 Returns true if the length of str1 is zero.

Here's an example of comparing strings in a script:

#!/bin/bash user ="likegeeks" if [$user = $USER] then echo "The user $user is the current logged in user" fi
As a result of executing the script, we get the following.


Comparing strings in scripts

Here's one feature of string comparison that's worth mentioning. Namely, the operators ">" and "<» необходимо экранировать с помощью обратной косой черты, иначе скрипт будет работать неправильно, хотя сообщений об ошибках и не появится. Скрипт интерпретирует знак «>» as an output redirection command.

Here's what working with these operators looks like in code:

#!/bin/bash val1=text val2="another text" if [ $val1 \>
Here are the results of the script.


String comparison, warning given

Please note that the script, although executed, issues a warning:

./myscript: line 5: [: too many arguments
To get rid of this warning, we enclose $val2 in double quotes:

#!/bin/bash val1=text val2="another text" if [ $val1 \> "$val2" ] then echo "$val1 is greater than $val2" else echo "$val1 is less than $val2" fi
Now everything works as it should.


String comparison

Another feature of the operators “>” and “<» заключается в том, как они работают с символами в верхнем и нижнем регистрах. Для того, чтобы понять эту особенность, подготовим текстовый файл с таким содержимым:

Likegeeks likegeeks
Let's save it, giving it the name myfile , and then run the following command in the terminal:

Sort myfile
It will sort the lines from the file like this:

Likegeeks Likegeeks
The sort command, by default, sorts strings in ascending order, that is, the lowercase letter in our example is smaller than the uppercase one. Now let's prepare a script that will compare the same strings:

#!/bin/bash val1=Likegeeks val2=likegeeks if [ $val1 \> $val2 ] then echo "$val1 is greater than $val2" else echo "$val1 is less than $val2" fi
If you run it, it turns out that everything is the other way around - the lowercase letter is now larger than the uppercase one.


The sort command and comparing strings in a script file

In comparison commands, uppercase letters are smaller than lowercase letters. String comparison here is done by comparing the ASCII codes of the characters, the sort order thus depends on the character codes.

The sort command, in turn, uses the sort order specified in the system language settings.

File checks

Perhaps the following commands are used most often in bash scripts. They allow you to check various conditions regarding files. Here is a list of these commands.
-d file Checks whether the file exists and is a directory.
-e file Checks if the file exists.
-f file Checks whether the file exists and is a file.
-r file Checks whether the file exists and is readable.
-s file Checks if the file exists and is not empty.
-w file Checks whether the file exists and is writable.
-x file Checks whether the file exists and is executable.
file1 -nt file2 Checks if file1 is newer than file2 .
file1 -ot file2 Checks if file1 is older than file2 .
-O file Checks whether the file exists and is owned by the current user.
-G file Checks whether a file exists and whether its group ID matches the current user's group ID.

These commands, as well as many others discussed today, are easy to remember. Their names, being abbreviations of various words, directly indicate the checks they perform.

Let's try one of the commands in practice:

#!/bin/bash mydir=/home/likegeeks if [ -d $mydir ] then echo "The $mydir directory exists" cd $ mydir ls else echo "The $mydir directory does not exist" fi
This script, for an existing directory, will display its contents.


Listing the contents of a directory

We believe that you can experiment with the remaining commands yourself; they are all used according to the same principle.

Results

Today we talked about how to get started writing bash scripts and covered some basic things. In fact, the topic of bash programming is huge. This article is a translation of the first part of a large series of 11 materials. If you want to continue right now, here is a list of the originals of these materials. For convenience, the translation of which you just read is included here.

Related publications