05.09.2019
Home / Mozilla firefox / Running a PHP script on a cron schedule. When not everything is so clear. Scripting on Bash

Running a PHP script on a cron schedule. When not everything is so clear. Scripting on Bash

In this article I will talk about running Shell scripts (* .sh) on Ubuntu

* .Sh file   this is a script, a script in the system Linux.
  When it starts, the commands written to it are executed in turn.

This is actually just a text file with instructions for the Linux system, which are executed in sequence.

Let's write a simple .sh script that we run on our system.

Create a text file in your home directory, open it and write the following lines into it:

Shell

#! / bin / bash echo "Hello World"

#! / bin / bash

echo "Hello World"

Save it like hello.sh
  You will get this text file in the home directory:

So we created sh script.

How to run sh script from command line?

To do this, you need:
1. Go to the script location directory using the console command cd. Since we saved this script in the home directory, we don’t need to go to any directory.

2.   Make our file executable.
  To do this, enter the chmod + x command and the script file name:

chmod + x hello.sh

3.   Now run it:

You can also run the following command:

If everything is done correctly, then the console will display "Hello world":


How to run sh in a graphical interface (GUI)?

1. Go to the directory with our sh script:

Tab "Behavior"   in point " Executable text files"should be selected either" Ask every time "or" Run executable text files on opening ".
The difference between them is that if you select "Ask every time", then you will have a choice: run the script in the console or in the graphical interface. In the second case, the launch will only be in graphical mode.

Now, your sh script will be launched with a double click.

But if you want create shortcut for sh script   in system   Ubuntu   then read my next article.

To create and execute a script in the script area, follow the steps described.

In the scripting area, you can open and edit the file type. We are currently interested in the following types of Windows PowerShell files: script files (PS1), script data files (PSD1), and script module files (PSM1). These file types have syntax highlighting in the script area editor. Other standard files that can be opened in the script area are configuration files (PS1XML), XML files, and text files.

Create a new script file

Press button Create File   and select Create. The created file will appear in a new tab. By default, a script type file (PS1) is created, but it can be saved with a new name and extension. Multiple script files can be created on the same PowerShell tab.

Opening an existing script

Press button Open...   on the toolbar or open the menu File   and select Open. In the dialog box Open   Select the file you want to open. An open file will appear in a new tab.

File path display

Script run

Press button Execute script   on the toolbar or open the menu File   and select Run.

Running part of the script

  1. In the script area, select the part of the script.
  2. On the menu File   select or on the toolbar click Run selection.

    Stop running script

    Click on the toolbar button Stop execution, press CTRL + BREAK or in the menu File   select item Stop execution. Pressing CTRL + C will also work if there is no selected text, otherwise the copy function will work for the selected text.

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 the packages. This is just an example and there are a lot of such actions, even taking backup and uploading the 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 consider writing scripts on Bash, consider the basic operators, as well as how they work, so to speak, bash scripts from scratch.

Scripting Basics

A script, or as it is also called a script, is a sequence of commands that the interpreter program reads and executes in turn, in our case it is a command-line program - bash.

A script is a plain text file that lists the usual commands that we used to enter manually, as well as the program that will execute them. The loader that will execute the script does not know how to work with environment variables, so it needs to be given the exact path to the program that needs to be run. And then he will already pass your script to this program and execution will begin.

The simplest example of a script for the Bash shell:

! / bin / bash
  echo "Hello world"


The echo utility displays the string passed to it in the parameter on the screen. The first line is special, it sets 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's 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 it is not just a text file, but a program and it needs to be executed, open the file, recognize the interpreter and execute. If no interpreter is specified, the default user interpreter will be used. But since not everyone uses bash, you need to specify this explicitly.

To do:

chmod ugo + x script_file

Now we execute our small first program:

./ script file


Everything is working. You already know how to write a small script, say for updating. As you can see, scripts contain the same commands that are executed in the terminal, it is very simple to write them. But now we will complicate the task a bit. Since the script is a program, it needs to make some decisions by itself, store the results of command execution and execute loops. All this allows you to do the shell Bash. True, everything is much more complicated here. Let's start with a simple one.

Script variables

Writing scripts on Bash rarely does without saving temporary data, which means creating variables. Not a single programming language can do without variables, and our primitive shell language, too.

You may have previously encountered environment variables. So, these are the same variables and they also work by themselves.

For example, declare a string variable:

string \u003d "Hello world"

The value of our string is in quotation marks. But in fact, quotation marks are not always needed. The basic principle of bash is preserved here - space is a special character, delimiter, so if you do not use quotation marks world will already be considered as a separate command, for the same reason we do not put spaces before and after the equal sign.

To display the value of a variable, use the $ character. For example:

We modify our script:

! / bin / bash
  string1 \u003d "hello"
  string2 \u003d world
  string \u003d $ string1 $ string2
  echo $ string

And check:

Bash does not distinguish between variable types in the same way as high-level languages, for example, C ++, you can assign a variable either a number or a string. Equally, all this will be considered a string. The shell only supports merging strings, for this just write the variable names in a row:

! / bin / bash
  string1 \u003d "hello"
  string2 \u003d world
  string \u003d $ string1 $ string2 \\ and \\ me
  string3 \u003d $ string1 $ string2 "and me"
  echo $ string3


We check:

Please note that, as I said, quotation marks are optional if there are no special characters in the string. Take a closer look at both ways of merging strings, the role of quotation marks is also demonstrated here. If you need more sophisticated methods for processing strings or arithmetic operations, this is not part of the shell's capabilities; ordinary utilities are used for this.

Variables and command output

Variables would not be so useful if it was impossible to write the result of the utilities in them. To do this, use the following syntax:

$(team )

With this construct, the output of the command will be redirected directly to where it was called, 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 \u003d "hello world"
  string2 \u003d $ (date)

string \u003d $ string1 $ string2


Now you know enough about variables, and you are ready to create a bash script, but there is more to come. Further we will consider the parameters and control structures. Let me remind you that these are all ordinary bash commands, and you do not have to save them in a file, you can execute them immediately on the go.

Script options

It is not always possible to create a bash script that is independent of user input. In most cases, you need to ask the user what action to take or which file to use. When the script is called, we can pass parameters to it. All these parameters are available in the form of variables with names in the form of numbers.

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

! / bin / bash
  echo $ 1



Control constructions 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 pretty complicated topic, but it is very important in order to create a bash script.

In Bash, to check conditions, there is a Syntax command like this:

if condition_command
then
team
else
team
fi

This command checks the termination code of the conditional command, and if 0 (success), it executes the command or several commands after the word then, if the termination code 1 is executed with the else block, fi means the completion of the command block.

But since we are most often interested in not the return code of the command, but the comparison of strings and numbers, the command [[was introduced, which allows you to perform various comparisons and issue a return code depending on the comparison result. Its syntax is:

[[parameter1 operator parameter2]]

For comparison, operators that are already familiar to us are used<,>, \u003d,! \u003d, etc. If the expression is true, the command will return 0, if not - 1. You can test its behavior in the terminal a little. The return code of the last command is stored in the variable $ ?:


Now combining all this and get a script with a conditional expression:

! / bin / bash
  if [[$ 1\u003e 2]]
  then
  echo $ 1 "greater than 2"
  else
  echo $ 1 "less than 2 or 2"
  fi



Of course, this design has more powerful features, but it is too complicated to consider them in this article. Maybe I'll write about it later. In the meantime, move on to the cycles.

Script cycles

The advantage of programs is that we can indicate in several lines what actions need to be performed several times. For example, it is possible to write scripts in bash, which consist of only a few lines, and are executed for hours, analyzing the parameters and performing the necessary actions.

The first is a 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 it executes the commands located between do and done.

For example, iterate over five digits:

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



Or you can list all the files from the current directory:

for file in $ (ls -l); do echo "$ file"; done


As you understand, you can not only display names, but also perform the necessary actions, it is very useful when creating a bash script.

The second loop that we will consider is the while loop; it is executed while the condition command returns code 0, success. Consider the syntax:

while condition command
do
team
done

Consider an example:

! / bin / bash
  index \u003d 1
  while [[$ index< 5 ]]
  do
  echo $ index
  let "index \u003d index + 1"
  done



As you can see, everything is executed, 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 mention one more thing. Constructs such as while, for, if are designed to write in several lines, and if you try to write them in one line, you will get an error. Nevertheless, it is possible, for this, where there should be a line feed, put a dot with a coma ";". For example, the previous loop could be executed as a single line:

index \u003d 1; while [[$ index< 5 ]]; do echo $index; let "index=index+1"; done;

Everything is very simple. I tried not to complicate the article with additional terms and capabilities of bash, only the most basic. In some cases, you may need to make gui for a bash script, then you can use programs such as zenity or kdialog, it is very convenient to display messages to the user and even request information from him.

findings

Now you understand the basics of creating a script in linux and can write the script you need, for example, for backup. I tried to consider bash scripts from scratch. Therefore, far from all aspects were considered. Perhaps we will return to this topic in one of the following articles.

So far, we have considered running programs from the shell command line. However, for repeated sequences of commands, this is inconvenient. In such cases, you can save the sequence of commands to a file and run them not from the command line, but from such a file. Typically, such files with recorded commands are called scripts.

In the simplest case, a script can be created, for example, like this:

$ echo "ls | grep script"\u003e script

ls | grep script

Here we created a text file containing the ls and grep commands, and then executed these commands by calling the command interpreter and passing the script name as an argument. The command interpreter, having received the file name as an argument, read the commands from it and executed them.

This way of running scripts is not very convenient. It differs from calling system commands: here it is required to indicate the name of the command interpreter on the command line and, in general, the full path to the script to be executed, while for compiled system commands it is enough to enter the name of the command itself. In addition, for * nix operating systems, there are several alternative shells with different command syntax. There are a large number of different interpretive programming languages, programs for which are also executed in the form of scripts and run using the corresponding interpreter programs. Thus, a way is required to indicate to the system which particular interpreter should execute this or that script.

The name of the program that should interpret the sequence of commands recorded in a text file (script) can be specified in the script itself. This is done using a specially designed first line of the script, which usually looks something like

The first line consists of two # characters! (octotorp and exclamation mark), followed by the full path to the program that will process this script. In this case, it is an interpreter of bash commands. As a rule, interpreted programming languages \u200b\u200b(and the shell in particular) use the # character (octotorp) to highlight comments, that is, they will not interpret a similarly designed string.

As discussed in previous lab work,
* nix operating systems have file permissions. If the file has the right to execute it, the command interpreter will open it and read the first few characters of the file. If the beginning of the compiled program is detected there, then it will be launched, if the sequence of # # characters is found there, then the interpreter specified after it will be launched, to which the file name will be passed as an argument.

$ echo "#! / bin / bash"\u003e script

$ echo "ls | grep script" \u003e\u003e script

$ chmod a + x script

ls | grep script

Rwxr-xr-x 1 student student 29 Mar 20 09:35 script

Here we created an echo file by calling the two commands (note that in the second command we added the line to the file that has it), assigned this file the right to execute, checked the result (outputting the file through cat and checking the rights to it through ls -l) and launched it to run.

Note that the shell searches for executable files in specific places: / bin, / usr / bin, etc. To run the program from a non-standard place, you must specify the path to it, i.e., in this case, you cannot run the program as a script - instead of the script we created, the shell will run the standard script utility from / usr / bin.

Often, simple sequential execution is not enough - effective programming requires variables, conditional execution of commands, etc. The shell has its own language, which, in terms of its capabilities, approaches high-level programming languages. This language allows you to create programs ( shell-files, scripts), which may include language statements and UNIX commands.

Such files do not require compilation and are executed in interpretation mode, but they must have the right to execute (installed using the chmod command).

The script can be passed arguments at startup. Each of the first nine arguments is assigned a positional parameter from $ 1 to $ 9 ($ 0 is the name of the script itself), and these names can be accessed from the script text.

Before starting a discussion of some operators shell, you should pay attention to the use of certain characters in commands.

● \\ (backslash) is the cancel character for the special line feed character immediately following this character.

● "" (apostrophes) - used to frame the text passed as a single argument to the command.

● "" (double quotation marks) - used to frame text containing variable names for substitution ($ name) or standard commands enclosed in reverse apostrophe characters (`command`).

● `` (reverse apostrophes) - are used to execute the command concluded between them.

In addition, for the convenience of working with files, almost all shells interpret characters? (question mark) and * (asterisk), using them as file name patterns (so-called metacharacters):

●? - any one character;

● * - an arbitrary number of any characters.

For example, * .c denotes all files with the extension c,
  pr ???. * denotes files whose names begin with pr, contain five characters and have any extension.

If the question: “how to add the program to autoload?” - novice users find the answer quickly enough, then the question of running the script, when you turn it off / restart, confuses them. This article will describe a standard way for automatically executing commands when linux is turned on and off, as well as a simpler method for users who have gdm and a graphical interface installed, for example ubuntu.

Console option.

A bit of theory.
  You should be aware that Linux has 7 runlevels. However, only 6 can be used.
  As with all self-respecting programs, the countdown starts from 0-la.
  0 - Stop or shut down the system.
  1 - Single-user mode.
  2 - Multiuser mode, but without network support.
  3 - The same, but with a network.
  4 - Added for beauty. Not used.
  5 - Graphic mode with the loading of the X server.
  6 - Reboot.
  If you go to the / etc folder (on some distributions /etc/rc.d), you can see folders with 7 launch levels.

  For example, when you turn off the computer, all scripts from the rc0.d folder will be executed



  Here it should stop for more details. The fact is that the scripts themselves (or rather scripts) are not in this folder, but there are only links to files that are in the /etc/init.d folder. These scripts perform various tasks, depending on the start or stop parameter (for example, /etc/init.d/reboot start and /etc/init.d/reboot stop these are different commands, and /etc/init.d/reboot will not be work). If the first letter S is in the link, then the start parameter is supplied to the script, and if the letter K is (from the word kill), then the stop parameter is given. The number after the letter indicates the order in which the script is executed.
  For example, in the screenshot above, the /etc/init.d/hddtemp stop command will be executed first, and only later /etc/init.d/networking start.
Enough theory. Let's move on to practice.
  To add a command to startup, just place it in the /etc/rc.local file.

In this part of the article, nano will be used as an editor, but you can use your favorite editor, for example gedit.

sudo nano /etc/rc.local

And we put our teams just above the line with exit 0.
  In order for the commands to be executed before shutting down or rebooting, we need to create a script in the /etc/init.d folder

sudo nano /etc/init.d/ script_name

Paste the following code:

  #! / bin / sh
  case "$ 1" in
  start)
  echo "start signal sent"
;;
  stop)
  echo "stop signal sent"
  ;; esac

If only one signal is given, then just comment out the line by putting a # sign at the beginning of the command
  for example

...
  case "$ 1" in
  start)
#
;;
...

Now make the file executable:

sudo chmod + x /etc/init.d/ script_name

sudo update-rc.d script_name start 20 0 6. stop 1 0 6.

Points are important (both). Exploring the Internet, I got the impression that the syntax of this program sometimes changes. Actual examples can be seen on the command "man update-rc.d". Examples will be at the bottom.

This command will create 2 links in the / etc / rc directories 0 .d (second number in command) and / etc / rc 6 .d (the third number in the command). And at first the script with the stop parameter will be executed (since it costs 1), and only then with the start parameter (since it costs 20).
  If the second parameter is not needed, then you can run the command:

sudo update-rc.d script_name stop 1 0 6.

I advise you to put the priority higher (that is, the number after start or stop should be small), preferably less than 20. Otherwise, my computer sometimes freezes up when I try to reboot.

For users of ubuntu, and many other modern gdm distributions, you can use ...

Graphic option.

As for startup, you can use the method described.
  Or simply open the "automatically launched applications" command:

gnome-session-properties

To execute the script when the computer is turned off, put it in the file / etc / gdm / PostSession / Default

sudo gedit / etc / gdm / PostSession / Default

Right above the line exit 0.