Shell command language.


The command language shell (translated as shell, shell) is actually a very high-level programming language. In this language, the user controls the computer. Typically, after logging in, you begin interacting with the command shell. A sign that the shell is ready to receive commands is the prompter it displays on the screen. In the simplest case it is one dollar (“$”). Shell is not necessary and the only command language (although it is the one that is standardized within the POSIX standard mobile systems). For example, the cshell language is quite popular; there are also kshell, bashell and others. Moreover, each user can create his own command language. Can simultaneously work with different command languages ​​on one instance of the operating system. shell is one of many UNIX commands. That is, the “shell” command set includes the “sh” command - calling the “shell” interpreter. The first "shell" is called automatically when you log in and displays a programmer. After this, you can call any commands for execution, including the “shell” itself, which will create a new shell for you inside the old one. So for example, if you prepare the file "file_1" in the editor:

Echo Hello!

then this will be a regular text file containing the “echo” command, which, when executed, displays everything written to the right of it on the screen. You can make file "file_1" executable using the command "chmod 755 file_1". But it can be done by explicitly calling the "sh" ("shell") command:

Sh file_1

Sh< file1

The file can also be executed in the current shell instance. There is a specific command for this "." (dot), i.e.

File_1

Since UNIX is a multi-user system, you can even personal computer work in parallel on, say, 12 screens (change from screen to screen ALT/function key), having on each screen a new (or the same) user with his own command shell. You can also graphic mode X-Window also opens a large number of windows, and each window can have its own user with its own command shell... The core element of the shell language is the command.

Command structures:

Commands in the shell usually have the following format:

<имя команды> <флаги> <аргумент(ы)>

For example:

Ls -ls /usr/bin

Where ls is the name of the command to output the contents of the directory, -ls is the flags ("-" is a sign of flags, l is the long format, s is the volume of files in blocks), /usr/bin is the directory for which the command is executed. This command will display the contents of the /usr/bin directory in long format, and will add information about the size of each file in blocks. Unfortunately, this command structure is not always followed. The flags are not always preceded by a minus, and the flags are not always one word. Yes variety in the presentation of arguments. Commands with exotic formats include such “running” commands as cc - calling the C language compiler, tar - working with archives, dd - copying a file with conversion, find - searching for files and a number of others As a rule, the shell perceives the first word as a command. Therefore, on the command line

the first word will be decrypted by the shell as a command (concatenation), which will display a file called "cat" (the second word) located in the current directory. Command redirection Standard input (input) - "stdin" in UNIX OS is carried out from the terminal keyboard, and standard output (output) - "stdout" is directed to the terminal screen. There is also standard file diagnostic messages - "stderr", which will be discussed a little later. A command that can operate on standard input and output is called FILTER. The user has convenient means redirecting input and output to other files (devices). The ">" and ">>" symbols indicate output redirection. ls >file_1 The "ls" command will generate a list of files in the current directory and place it in the file "file_1" (instead of printing it to the screen). If the file "file_1" existed before, it will be overwritten by the new one.

Pwd >>file_1

pwd team will form full name current directory and will place it at the end of the file "file_1", i.e. ">>" appends to the file if it is non-empty. Symbols "<" и "<<" обозначают перенаправление ввода.

Wc -l

will count and display the number of lines in the file file_1.

Ed file_2<

will create the file "file_2" using the editor, directly from the terminal. The end of the input is determined by the character to the right "<<" (т. е. "!"). То есть ввод будет закончен, когда первым в очередной строке будет "!". Можно сочетать перенаправления. Так

Wc -l file_4

Wc -l >file_4

are performed in the same way: the number of lines in the file "file_3" is counted and the result is placed in the file "file_4". The means that combines the standard output of one command with the standard input of another is called a PIPELINE and is indicated by a vertical bar "|".

ls | wc -l

a list of files in the current directory will be sent to the input of the "wc" command, which will display the number of lines in the directory. The pipeline can also combine more than two commands, when all of them, possibly except the first and last, are filters:

Cat file_1 | grep -h result | sort | cat -b > file_2

This pipeline from the file "file_1" ("cat") will select all lines containing the word "result" ("grep"), sort ("sort") the resulting lines, and then number ("cat -b") and print the result in file "file_2". Because UNIX devices are represented by special files, they can be used in redirections. Special files are located in the "/dev" directory. For example, "lp" - print; "console" - console; "ttyi" - i-th terminal; "null" is a dummy (empty) file (device). Then, for example,

Ls > /dev/lp

will print the contents of the current directory, and file_1< /dev/null обнулит файл "file_1".

Sort file_1 | tee /dev/lp | tail -20

In this case, the file "file_1" will be sorted and printed, and the last 20 lines will also be printed on the screen. Let's go back to output redirection. Standard files are numbered:

0 - stdin, 1 - stdout 2 - stderr. If you do not want to have an error message on the screen, you can redirect it from the screen to the file you specify (or completely throw it away by redirecting it to the “empty device” file - /dev/null). For example, when executing the command

Cat file_1 file_2

which should display the contents of the files “file_1” and “file_2” sequentially on the screen, it will give you, for example, the following

111111 222222 cat: f2: No such file or directory

where 111111 222222 is the contents of file "file_1" and file "file_2" is missing, which the "cat" command reported to the standard diagnostic file, by default, as is the standard output represented by the screen. If you do not want such a message on the screen, you can redirect it to the file you specify:

Cat file_1 file_2 2>f-err

error messages will be sent (as indicated by the "2>" redirection) to the "f-err" file. By the way, you can send all the information to one file "ff" by using in this case design

Cat file_1 file_2 >>ff 2>ff

You can specify not only which standard file to redirect, but also which standard file to redirect to.

Cat file_1 file_2 2>>ff 1>&2

Here, first "stderr" is redirected (in append mode) to file "ff", and then standard output is redirected to "stderr", which by this point is file "ff". That is, the result will be similar to the previous one. The construction "1>&2" means that in addition to the number of the standard file to redirect to, you must put "&" in front; the entire structure is written without spaces.<- закрывает стандартный ввод. >- closes standard output. Command files. There are several options for allowing a text file to be used as a command. Let's use an editor to create a file called "cmd" containing one line like this:

Date; pwd; ls

You can call the shell as a command, denoted "sh", and pass it a "cmd" file as an argument or as a redirected input, i.e.

$ sh cmd

$sh

The result of executing any of these commands will be the date, then the name of the current directory, and then the contents of the directory. A more interesting and convenient option for working with a batch file is to turn it into an executable one, i.e. just make it a command, which is achieved by changing the security code. To do this, you must allow execution of this file. For example,

Chmod 711 cmd

will make the security code "rwx__x__x". Then a simple call

will execute the same three commands. The result will be the same if the file with the contents

Date; pwd; ls

is represented in the form: date pwd ls since the transition to another line is also a separator in the sequence of commands. Thus, executable files can be not only files obtained as a result of compilation and assembly, but also files written in the shell language. They are executed in interpretation mode using a shell interpreter

Debugging batch files

SHELL uses two mechanisms for debugging batch files. The first one is: set -v prints out the command file lines as they are read. This mode is used when searching for syntax errors. To use it, you do not need to modify the command file, for example: sh -v proc... here proc is the name of the command file. The -v switch can be used in conjunction with the -n switch, which prevents execution of subsequent commands (the set -n command blocks the terminal until the EOF flag is entered). The set -x command displays commands as they are executed, and the program lines are output to the terminal and their values ​​are substituted in place of the variables. To cancel the -x and -v switches, you can use the set command - and to install, assign the corresponding value to a macro variable. SHELL ENVIRONMENT (VARIABLES AND PARAMETERS) In the shell language, you can write batch files and use the "chmod" command to make them executable. After this, they are no different from other UNIX OS commands.

Shell variables

A shell variable name is a sequence of letters, numbers, and underscores starting with a letter. The value of a shell variable is a string of characters. The fact that there are only two types of data in the shell: a string of characters and a text file, on the one hand, makes it easy to involve end users in programming who have never done programming before, and on the other hand, causes a certain internal protest among many programmers who are accustomed to significantly greater diversity and greater flexibility of linguistic means. However, it is interesting to observe how highly qualified programmers, having become familiar with the “rules of the game” of the shell, write programs in it many times faster than in C, but, what is especially interesting, in some cases these programs run even faster than those implemented in C. A variable name is similar to the traditional idea of ​​an identifier, i.e. a name can be a sequence of letters, numbers, and underscores, starting with a letter or underscore. The assignment operator "=" can be used to assign values ​​to variables.

Var_1=13 - "13" is not a number, but a string of two digits. var_2="UNIX OS" - Double quotes (" ") are required here because there is a space in the string.

Other ways of assigning values ​​to shell variables are also possible. For example, the recording

DAT=`date`

causes the "date" command to be executed first (the backticks indicate that the enclosed command must be executed first), and the result of its execution, instead of being output to the standard output, is assigned as the value of a variable, in this case " DAT". You can also assign a value to a variable using the "read" command, which ensures that the value of the variable is received from the (keyboard) display in dialog mode. Usually the "read" command in the batch file is preceded by the "echo" command, which allows you to pre-display some message on the screen. For example:

Echo -n "Enter a three-digit number:" read x

When executing this portion of the command file, after the message is displayed

Enter a three-digit number:

the interpreter will stop and wait for a value to be entered from the keyboard. If you entered, say, "753" then this will become the value of the variable "x". One "read" command can read (assign) values ​​to several variables at once. If there are more variables in "read" than are entered (separated by spaces), the remaining ones are assigned an empty string. If there are more transmitted values ​​than variables in the "read" command, then the extra ones are ignored. When accessing a shell variable, you must precede the name with the "$" symbol. So the commands echo $var_2 echo var_2 will display on the screen

UNIX OS var_2 Escaping

Let's take a closer look at the escaping techniques used in the shell. Double quotes (" "), single quotes (" "), and backslashes (\) are used as escape devices. Their action is obvious from the examples: You can write several assignments in one line.

X=22 y=33 z=$x A="$x" B="$x" C=\$x D="$x + $y + $z" E="$x + $y + $z " F=$x\ +\ $y\ +\ $z

(the assignment G=$x+$y would fail because of the spaces) Then

Echo A = $A B = $B C = $C echo D = $D E = $E F = $F eval echo evaluated A = $A eval echo evaluated B = $B eval echo evaluated C = $C

Will be displayed on the screen

A = 22 B = $x C = $x D = 22 + 33 + 22 E = $x + $y + $z F = 22 + 33 + 22 evaluated A = 22 evaluated B = 22 evaluated C = 22

Let's give some more examples related to escaping line feeds. Let the variable "string" be assigned the value of a 2x3 "array": abc def Note that to avoid assigning extra spaces, the second line of the array starts from the first position of the following line: string="abc def" Then there are three options for writing the variable in the "echo" echo command $string echo "$string" echo "$string" will give respectively three different results: abc def $string abc def and the sequence of commands echo "str_1 str_2" > file_1 echo "str_1 str_2" > file_2 cat file_1 file_2 will give sequentially identical files file_1 and file_2: str_1 str_2 str_1 str_2 Note also that the backslash (\) not only escapes the character that follows it, which allows special characters to be used simply as characters representing themselves (it can also escape itself - \\), but in a command file, a backslash allows you to concatenate lines into one (escape the end of the line). For example, the command line example given earlier:

Cat file_1 | grep -h result | sort | cat -b > file_2

could be written in a batch file, say like

Cat file_1 | grep -h\result | sort | cat -b > file_2

By the way, the conveyor symbol also provides the effect of continuing the command line. In this case it might give a nicer result, like this:

Cat file_1 | grep -h result | sort | cat -b > file_2

Manipulations with shell variables Despite the fact that shell variables are generally perceived as strings, i.e. “35” is not a number, but a string of two characters “3” and “5”, in a number of cases they can be interpreted differently, for example as integers. The "expr" command has a variety of capabilities. Let's illustrate some with examples: Executing a batch file:

X=7 y=2 a=`expr $x + $y` ; echo a=$a a=`expr $a + 1` ; echo a=$a b=`expr $y - $x` ; echo b=$b c=`expr $x "*" $y` ; echo c=$c d=`expr $x / $y` ; echo d=$d e=`expr $x % $y` ; echo e=$e

will display on the screen

A=9 a=10 b=-5 c=14 d=3 e=1

The multiplication operation ("*") must be escaped, since in the shell this icon is perceived as a special character, meaning that any sequence of characters can be substituted in this place. With the "expr" command, not only (integer) arithmetic operations are possible, but also string ones:

A=`expr "cocktail" : "cock"` ; echo $A B=`expr "cocktail" : "tail"` ; echo $B C=`expr "cocktail" : "cook"` ; echo $C D=`expr "cock" : "cocktail"` ; echo $D

Numbers will be displayed on the screen showing the number of matching characters in the chains (from the beginning). The second line cannot be longer than the first:

4 0 0 0

Exporting variables UNIX OS has the concept of a process. A process occurs when a command is executed. For example, when typing "p" on the keyboard "process "p" is spawned. In turn, "p" can spawn other processes. Let us assume that "p" calls "p1" and "p2", which sequentially spawn the corresponding processes. Each process has its own environment - a set of variables available to it For example, before launching "p" there was already an environment in which some variables were already defined. Launching "p" spawns a new environment; "p1" and "p2" will already be generated in it. Variables are local to the process in which they declared, i.e. where they are assigned values. In order for them to be available to other spawned processes, they must be passed explicitly. To do this, use the built-in "export" command.

Options

Parameters can be passed to the command file. The shell uses positional parameters (that is, the order in which they appear is important). In the command file, the variables corresponding to the parameters (similar to shell variables) begin with the symbol "$", followed by one of the numbers from 0 to 9: Let "examp-1" be called with the parameters "cock" and "tail". These parameters go into the new environment under the standard names "1" and "2". The (standard) variable named "0" will store the name of the called calculation. When accessing parameters, the number is preceded by the dollar symbol "$" (as when accessing variables): $0 corresponds to the name of this command file; $1 is the first parameter in order; $2 second parameter, etc. Since the number of variables to which parameters can be passed is limited to one digit, i.e. 9th (“0”, as already noted, has a special meaning), then to transfer a larger number of parameters a special “shift” command is used. The "set" command provides a unique approach to parameters. For example, fragment

Set a b with echo first=$1 second=$2 third=$3

will display on the screen

First=a second=b third=c

those. the "set" command sets the parameter values. This can be very convenient. For example, the "date" command displays the current date, say "Mon May 01 12:15:10 2000", consisting of five words, then

Set `date` echo $1 $3 $5

will display on the screen

Mon 01 2000

The "set" command also allows you to control the execution of the program, for example: set -v lines are output to the terminal, read by the shell. set +v cancels the previous mode. set -x prints commands to the terminal before execution. set +x cancels the previous mode. The "set" command without parameters displays the state of the software environment to the terminal.

Shell substitutions

Before directly interpreting and executing commands contained in batch files, the shell executes different kinds substitutions: 1. SUBSTITUTION OF RESULTS. All commands enclosed in backquotes are executed and the result is substituted in their place. 2. SUBSTITUTION OF VALUES OF PARAMETERS AND VARIABLES. That is, words starting with "$" are replaced with the corresponding values ​​of variables and parameters. 3. INTERPRETING GAPS. Escaped spaces are ignored. 4. GENERATION OF FILE NAMES. Words are checked for the presence of special characters ("*", "?","") and the corresponding generations are performed. Software Environment Every process has an environment in which it runs. Shell uses a number of these environment variables. If you type the "set" command without parameters, the screen will display information about a number of standard variables created at login (and then passed on to all your new processes "inherited"), as well as variables created and exported by your processes. The specific type and content of the information output depends to a large extent on what version of UNIX is used and how the system is installed.

The result of executing the set command without parameters (not complete):

HOME=/root PATH=/usr/local/bin:/usr/bin:/bin:.:/usr/bin/X11: IFS= LOGNAME=sae MAIL=/var/spool/mail/sae PWD=/home/ sae/STUDY/SHELL PS1=$(PWD):" " PS2=> SHELL=/bin/bash

Let's comment on the values ​​of the variables. HOME=/root is the name of the home directory where the user ends up after logging in. That is, having entered the name and password correctly, I will find myself in the “/root” directory. PATH=/bin:/usr/bin:.:/usr/local/bin:/usr/bin/X11 - this variable specifies the sequence of files that the shell looks for in search of a command. File names are separated here by colons. The viewing sequence corresponds to the order of names in the trail. But initially the search occurs among the so-called built-in commands. The built-in commands include the most commonly used commands, such as "echo", "cd", "pwd", "date". After this, the system looks through the “/bin” directory, which may contain the commands “sh”, “cp”, “mv”, “ls”, etc. Then the directory "/usr/bin" with the commands "cat", "ss", "expr", "nroff", "man" and many others. Next, the search takes place in the current directory (".", or another designation "empty", i.e. ""), where the commands you wrote are most likely located. After typing the command line and pressing "shell" (after performing the necessary substitutions) recognizes the name corresponding to the command and searches for it in the directories listed in PATH. If the command is placed outside of these directories, it will not be found. If there are several commands with the same name, the one located in the directory viewed first will be called. PATH, like other variables, can be easily changed by adding, rearranging, or deleting directories. IFS= (Internal Field Separator) lists characters that serve to separate words (fields). These are “space”, “tab” and “line feed”, so here nothing is visible to the left of the assignment and two lines are occupied. LOGNAME=root - login name (“user name”). MAIL=/var/spool/mail/root - the name of the file into which (e-mail) mail is received. PWD=/root - name of the current directory PS1=$(PWD): " " - type of directory. In this case, the prompter will display the name of the current directory followed by a colon and a space. That is, there will be "/root: ". PS2=> - this prompt (here ">") is used as an invitation to continue entering (in the next line) an unfinished command. For example, type the opening bracket "(" and after pressing in the next line you will see this prompter. If you don't know what to do next, type the closing bracket ")" and it will disappear. SHELL=/bin/sh - This variable specifies the shell the user is using. In this case, the standard shell ("sh") is used. The initial environment is installed automatically upon login using files like "/etc/rc" and "/etc/.profile". One way to simply change the environment (for example, command search path, program type, shell type, screen color, etc.) is by placing this information in your home directory in a specialized ".profile" file ($(HOME)/. profile), assigning required values environment variables. That is, call this file into the editor and write whatever you want). Then, every time you log in, this file will automatically be executed and install a new environment. This file MUST be placed in your HOME directory(entry directories). It should be kept in mind that file names starting with a dot generally have a special status. Thus, they are not displayed on the screen with a simple "ls" command - you must call this command with the "-a" flag. By the way, they are not destroyed indiscriminately by the “rm *” command. The shell interpreter itself automatically assigns values ​​to the following variables (parameters): ? the value returned by the last command; $ process number; ! background process number;

  1. the number of positional parameters passed to the shell;
  • list of parameters as one line;

@ list of parameters, as a set of words; - flags passed to the shell. When accessing these variables (that is, when using them in a command file - shell program), you should put "$" in front. An important role in creating unique files is played by the special variable "$$", the value of which corresponds to the number of the process performing this calculation. Each new calculation performed by a computer initiates one or more processes that automatically receive numbers in order. Therefore, using the process number as a file name, you can be sure that each new file will have a new name (will not be written in place of an existing one). The advantage is also the main disadvantage of this method of naming files. It is not known what names will be assigned to the files. And, if within this process you can find a file “without looking”, i.e., by accessing it using $$, then such files can be easily lost. This creates additional problems when debugging programs. Calling the interpreter After registering the user in the system (using the login command), the SHELL language interpreter is called. If the user's registration directory contains a .profile file, then before at least one command is received from the terminal, the interpreter executes this file (it is assumed that the .profile file contains commands). When calling, the following keys can be specified: -c string Commands are read from the given string. -s Commands are read from standard input. Interpreter messages are written to a standard diagnostics file. -i Interactive operating mode. If the first character of the "0" parameter is a - sign, then the commands are read from the .profile file.

PROGRAM STRUCTURES===

As in any programming language, shell text can contain comments. The "#" symbol is used for this. Everything that is on the line (in the command file) to the left of this character is perceived by the interpreter as a comment. For example,

# This is a comment.

Like any procedural programming language, the shell language has operators. A number of operators allow you to control the sequence of command execution. In such operators, it is often necessary to check the condition, which determines the direction in which the calculations continue.

Test("") command

The test command checks that a certain condition is met. Shell language select and loop statements are generated using this (built-in) command. Two possible command formats:

Test condition

[ condition ]

we will use the second option, i.e. Instead of writing the word “test” before the condition, we will enclose the condition in parentheses, which is more common for programmers. In fact, the shell will recognize this command by the opening bracket "[" as the word corresponding to the "test" command. There must be spaces between the brackets and the condition they contain. There must also be spaces between the values ​​and the comparison or operation symbol. The shell uses conditions of various "types". FILE CHECKING CONDITIONS: -f file file "file" is a regular file; -d file file "file" - directory; -с file file "file" is a special file; -r file has permission to read the file "file"; -w file has permission to write to file "file"; -s file file "file" is not empty.

CONDITIONS FOR TESTING STRINGS: str1 = str2 strings "str1" and "str2" match; str1 != str2 strings "str1" and "str2" are not the same; -n str1 string "str1" exists (non-empty); -z str1 string "str1" does not exist (empty). Examples.

X="who is who"; export x; [ "who is who" = "$x" ]; echo $? 0 x=abc ; export x ; [ abc = "$x" ] ; echo $? 0 x=abc ; export x ; [ -n "$x" ] ; echo $? 0 x="" ; export x ; [ -n "$x" ] ; echo $? 1

Additionally, there are two standard condition values ​​that can be used in place of condition (no parentheses are needed for this). CONDITIONS FOR COMPARING INTEGERS: x -eq y "x" is equal to "y", x -ne y "x" is not equal to "y", x -gt y "x" is greater than "y", x -ge y "x" is greater than or equal to "y", x -lt y "x" less than "y", x -le y "x" less than or equal to "y". COMPLEX CONDITIONS: Implemented using standard logical operations: ! (not) reverses the exit code value. -o (or) matches logical "OR". -a (and) matches logical "AND".

Conditional statement "if"

In general, the "if" statement has the structure

If condition then list

Here "elif" a shortened version of "else if" can be used along with the full one, i.e. nesting of an arbitrary number of "if" statements (as well as other statements) is allowed. Of course, the “list” in each case must be meaningful and acceptable in the given context. The most truncated structure of this operator

If condition then list fi

if the condition is met (usually this is where the completion code "0" is received), then the "list" is executed, otherwise it is skipped. Examples: Let "if-1" be written

If [ $1 -gt $2 ]

then pwd else echo $0: Hello!

Then calling if-1 12 11 will produce /home/sae/STUDY/SHELL and if-1 12 13 will produce if-1: Hello!

Call operator ("case")

The "case" selection operator has the structure:

Case string in

template) list of commands;; template) list of commands;; ... template) list of commands;;

Here "case", "in" and "esac" are function words. The "string" (this can be a single character) is compared with the "pattern". The "command list" of the selected line is then executed. The ";;" at the end of the selection lines looks unusual, but write ";" here it would be a mistake. Multiple commands can be executed for each alternative. If these commands are written on one line, then the symbol ";" will be used as a command separator. Typically the last selection line has the pattern "*", which in a "case" structure means "any value". This line is selected if the value of the variable (here $z) does not match any of the previously written patterns delimited by the ")" bracket. The values ​​are viewed in the order they were written.

Enumerated loop operator ("for")

The "for" loop operator has the structure:

For name

do list of commands done where "for" - function word defining the type of loop, “do” and “done” are service words that highlight the body of the loop. Let the "lsort" command be represented by a batch file

For i in file_1 file_2 file_3 do proc_sort $i done

In this example, the name "i" acts as a loop parameter. This name can be considered as a shell variable to which the listed values ​​are sequentially assigned (i=file_1, i=file_2, i=file_3), and the "proc_sort" command is executed in a loop. The form "for i in *" is often used, meaning "for all files in the current directory". Let "proc_sort" in turn be represented by a batch file

Cat $1 | sort | tee /dev/lp > $(1)_sorted

those. sorted sequentially specified files, the sorting results are printed ("/dev/lp") and sent to the files file_1_sorted file_2_sorted and file_3_sorted

Loop statement with true condition ("while")

The "while" structure, which also performs calculations, is preferable when the exact list of parameter values ​​is unknown in advance or this list must be obtained as a result of calculations in a loop. The "while" loop statement has the structure:

While condition

do list of commands done where "while" is an auxiliary word that determines the type of loop with a true condition. The list of commands in the loop body (between “do” and “done”) is repeated until the condition remains true (i.e., the completion code of the last command in the loop body is “0”) or the loop is not interrupted from the inside by special commands ( "break", "continue" or "exit"). When you first enter the loop, the condition must be true. The "break [n]" command allows you to break out of a loop. If "n" is missing, then it is equivalent to "break 1". "n" indicates the number of nested loops from which to exit, for example, "break 3" - exit from three nested loops. Unlike the "break" command, the "continue [n]" command only stops the execution of the current loop and returns to the BEGINNING of the loop. It can also be with a parameter. For example, "continue 2" means exit to the beginning of the second (counting from depth) nested loop. The "exit [n]" command allows you to exit the procedure altogether with a return code of "0" or "n" (if the "n" parameter is specified). This command can be used in more than just loops. Even in a linear sequence of commands, it can be useful in debugging to stop the (current) calculation at a given point.

Loop statement with false condition ("until")

The "until" loop operator has the structure:

Until condition

do list of commands done where "until" is an auxiliary word that determines the type of loop with a false condition. The list of commands in the body of the loop (between "do" and "done") is repeated until the condition remains false or the loop is interrupted from the inside by special commands ("break", "continue" or "exit"). The first time you enter the loop, the condition should not be true. The difference from the "while" operator is that the loop condition is checked for falsehood (for a non-zero exit code of the last command of the loop body) and is checked AFTER each (including the first!) execution of commands in the loop body. Example.

Until false do

read x if [ $x = 5 ] then echo enough ; break else echo some more fi

Here the program waits in an infinite loop for words to be entered (repeating the phrase "some more" on the screen) until "5" is entered. After this, "enough" is issued and the "break" command stops executing the loop.

Empty operator

The empty statement has the format

:

Doing nothing. Returns the value "0".

Functions in shell

The function allows you to prepare a list of shell commands for subsequent execution. The function description looks like:

Name() (command list)

after which the function is called by name. When the function is executed, no new process is created. It runs in the environment of the corresponding process. The function's arguments become its positional parameters; the name of the function is its zero parameter. You can interrupt the execution of a function using the "return [n]" operator, where (optional) "n" is the return code.

Interrupt handling ("trap")

It may be necessary to protect program execution from interruption. Most often you encounter the following interruptions corresponding to signals: 0 exit from the interpreter, 1 hang up (disconnection of the remote subscriber), 2 interruption from , 9 destruction (not intercepted), 15 end of execution. To protect against interrupts, there is a "trap" command, which has the format:

Trap "command list" signals

If interrupts occur in the system, whose signals are listed separated by a space in the “signals”, then the “command list” will be executed, after which (if the “exit” command was not executed in the command list) control will return to the interruption point and execution of the command file will continue. For example, if you need to delete files in “/tmp” before interrupting the execution of a command file, then this can be done with the “trap” command:

Trap "rm /tmp/* ; exit 1" 1 2 15

which precedes other commands in the file. Here, after deleting the files, the command file will be exited.

As with most interactive systems, the traditional UNIX user interface is based on the use of command languages. To put it somewhat tautologically, we can say that the command language is the language in which the user interacts with the system interactively. Such a language is called a command language because each line entered from the terminal and sent to the system can be considered as a command from the user to the system. One of the achievements of the UNIX OS is that the command languages ​​of this operating system are well defined and contain features that bring them closer to programming languages.

If we consider the category of command languages ​​from the point of view of the general direction of human-computer interaction languages, then they naturally belong to the family of interpreted languages. Let's briefly describe the difference between compiled and interpreted computer languages. A language is said to be compiled if it requires that any complete language construct be so closed that it can be processed in isolation without the need for additional language constructs. Otherwise, understanding of the language construct is not guaranteed.

The main advantage of interpreted languages ​​is that when they are used, the program is written “incrementally” (in step-by-step mode), i.e. a person makes a decision about his next step depending on the system's reaction to the previous step. In principle, preference for compiled or interpreted languages ​​is a matter of personal taste for the individual.

The peculiarity of command languages ​​is that in most cases they are not used for programming in the usual sense of the word, although any program can be written in a developed command language. The correct style of using a command language is to use it primarily for direct interaction with the system, using the ability to compose command files (scripts or scripts in UNIX OS terminology) to save repetitive routine procedures.

Programs designed to process command language constructs are called command interpreters. Unlike compiled programming languages ​​(such as C or Pascal), for each of which there are usually many different compilers, a command language is usually inextricably linked to a corresponding interpreter. When we talk below about various representatives of UNIX OS command languages ​​belonging to the shell family, then each time we will also mean the corresponding interpreter by the same name.

Computer control system, its work processes, internal memory and user actions in general. We invite the reader to take a closer look at the OS from this aspect.

What is this?

Of course, first of all, the operating system is a control system. Let's give a more complete definition of an OS: a complex of control and processing applications. On the one hand, they act as an interface between computer system devices and application applications and programs. On the other hand, the operating system is a management system certain devices,computational processes. It is the OS that effectively distributes computing resources between computing processes and reliably organizes calculations in the system.

If we look at the logical structure of a typical computing system, the OS will occupy an intermediate position between devices that have their own microarchitecture, machine language, embedded firmware on one side and application applications on the other.

As for software developers, the OS allows them to abstract from the features of the functioning and implementation of devices, providing the minimum required functional set.

In most computing systems, the operating system is the control system. This is the main, most important (and in some cases the only) part of the system software. If we look at specific examples, the most popular OS will be the Microsoft product - Windows (“Windows”).

Operating systems management

Many people are interested in the question of whether there are specialized programs to manage operating systems? This construction of the sentence is incorrect. After all, the operating system itself is a set of programs that manage computer resources and establish a dialogue between the user and the device.

That's why it's all about oil and butter: control over control. There is a complex application programs, which are “managed” by the operating system.

Basic OS features

Operating system - computer resource management. This the main task OS. A set of the following functions follows directly from it:

  • Execution of various program requests. Such as: input and output of information, starting and stopping application programs and applications, freeing, allocating memory, etc.
  • Providing standardized access to peripheral devices (for example, I/O devices).
  • Managing computer RAM: distributing it between active processes, general organization virtual memory.
  • Controlling access to data located on non-volatile media. For example, on optical hard drives and so on.
  • Saving information about system errors.
  • Providing a user interface.

Command languages ​​- dialogue with the user

How is operating system data managed? As in most interactive systems, the user can influence the functioning of the OS using special command languages.

What is this? Command language is the language in which a person interacts with an interactive system. Why team? Each line that is entered by a person on the terminal and sent to the system is perceived as a user command in relation to the OS.

If we look at the niche of command languages ​​from the outside common system languages ​​of human-computer interaction, then they will be classified as interpreted. Their antagonists are complimentary languages.

Let's consider the difference between them: a language is called complimentary if it requires that any construction on it be so closed that it could provide the possibility of isolated processing without the use of additional language constructions. Otherwise, understanding cannot be guaranteed. Interpreted languages ​​are understandable even without meeting such a requirement.

Process management

Let's look at process management in operating systems. The OS controls the following activities associated with them:

  • Both creating and deleting processes.
  • Synchronization.
  • Planning.
  • Communication.
  • Resolving deadlocks.

It should be noted that during its “life” the process changes its own state many times:

  • New. The newly created process.
  • Executable. At this time, program commands are executed in the CPU.
  • Waiting. The process is waiting for some event to complete. Most often, the last operation is the I/O operation.
  • Ready. A process that is waiting for the CPU to become free.
  • Completed. The process has completely completed its work.

Note that the transition from one such state to another cannot be arbitrary.

In many operating systems, information about each process is stored in a special table. operational processes. Each of them is represented in the operating system by a specific set of data. This is a set of values ​​and parameters that characterize the current state of the process. It is used by the OS to control the passage of a specific process through the computer.

How is the computational process created in this case? There are two ways: directly entered from the keyboard with a command or through a batch file. The process involves, at a minimum, downloading the application and creating special control blocks.

As a result of this, high-quality new process, which is later incorporated into the multi-program mix. After this, the OS begins to see it. The process itself is in a state of readiness.

OS process table

The processes thus function and operate under the control of the operating system. Let's present a brief table of OS processes:

  • Section "Process Control": registers, program counters, stack pointers, process state, process priority, scheduling parameters, process identifiers, parent processes, process groups, process start time, processor time used.
  • Section "Memory Management": pointers to text segments, pointers to data segments, pointers to stack segments.
  • "File Management": working directories, root directory, user IDs, file handles, group IDs.

Memory management

Let's look at another important aspect: memory management in operating systems.

It should be noted that it is memory - most important resource, which requires the most careful management by multiprogram operating systems. What ensures its special role? The processor can execute instructions from applications and programs only if they are located in computer memory.

In early operating systems, memory management was simple: the program and its necessary data were loaded from some external data storage device (optical disk, punched paper tape, magnetic tape, etc.) into the computer's memory. With the advent of multiprogramming, the situation has changed radically. Arose new task: Allocate computer memory among multiple running applications.

The main tasks of the OS in memory management

We continue to talk about management tools in operating systems. Let us highlight the main tasks of the OS in managing computer memory:

  • Monitoring free and used memory segments.
  • Memory allocation certain processes and her release upon completion.
  • Removing both code and process data from random access memory to disk - full or partial. It is used when the volume of main memory is not enough to accommodate all processes. When the OP is released, the operating system returns the processes to their place.
  • Setting addresses of programs and applications to specific zones of physical memory.

Additional OS functions for PC memory management

Let's consider additional tasks which the system performs in this case:

  • Dynamic allocation of device memory. This means fulfilling application requests to allocate additional memory to them for the duration of execution.
  • Creation of new information service structures - buffers, flow and process descriptors.
  • Memory protection. Consists of preventing a specific running process from writing or reading data related to another activity.

As we have already said, there is not enough RAM for all processes. Therefore, the OS connects an external disk one. This consists of the following system actions:

  • Paging. Here the process is completely loaded into memory for further work.
  • Virtual memory. In this case, the process is partially loaded to perform some task.

Let us note once again that large processes are only temporarily offloaded by the OS onto the hard drive. After the RAM is freed, the system returns them to their place.

An operating system is a whole set of software that manages a computer. That is, its memory, processes, resources. Another important OS function: build interaction computer system with a person, a user. This is achieved by using special tools - command languages.

Rental block

Command language processor- special purpose program. It is designed to enter and process OS commands entered by the user, as well as to display system messages on the computer display. The standard command processor for MS DOS is the COMMAND.COM program.

The main elements that make up the MS DOS operating system are the following components:

1) BIOS- Base Input Output System, basic system input/output - includes programs for initial testing of the functioning of computer nodes; These programs check the operation of PC devices and memory when the power is turned on. In addition, the BIOS includes a program bootstrap OS and standard device drivers.

2) OS bootloader- a short program located in the first sector of a floppy disk or MS DOS disk. The purpose of this program is to read into memory two MS DOS programs that make up the core of this OS (files io.sys, msdos.sys).

3) Files IO.SYS And MSDOS.SYS- form the core of the OS. These files are loaded at the initial stage and actually represent the operating system, ensuring the functioning of all elements of the OS and the organization of I/O.

4) COMMAND.COM- command processor. Enters commands from the keyboard and displays user messages on the display.

· automatically, when power is turned on;

· when you press the “Reset” button on the front panel of the system unit;

· when you press the Ctrl-Alt-Del key combination (golden combination).

a) the boot program is launched from the BIOS;

b) the boot program tries to read the OS bootloader from floppy disk A:, then disk C:, then from CD-ROM. Or in another order, in accordance with the order specified in CMOS;

c) the bootloader reads the system kernel IO.SYS, MS-DOS.SYS and transfers control;

d) after booting, the system kernel first reads the CONFIG.SYS file from the root directory. As this file is executed, the computer drivers are loaded and the OS parameters are set. If CONFIG.SYS is missing, then the default OS parameters are set;

e) the OS kernel launches the COMMAND.COM command processor and control is transferred to it;

f) the COMMAD.COM program reads and executes the AUTOEXEC.BAT file from the root directory. If this file is missing, then the program requests the current date and time. The value of these parameters can be left at default by pressing the key ;

g) The OS issues a prompt invitation. This means that the system is ready for use.

We have the biggest information base in RuNet, so you can always find similar queries

This topic belongs to the section:

OS

Tasks of operating systems. Software, software, OS functions, software modules,Process management. CPU. Algorithms.

Formation of pricing policy

The reality and role of pricing policy in the current economy. Basic principles of pricing policy formation. Price formation on markets of various types. Pricing for different types of pricing policies. Pricing at various stages of a product’s life cycle

General surgery. Questions

Economic systems, their main types.

Economic theory. Economic systems. Property as the basis of production relations. Forms of ownership

System of law: concept and structure

The system of law is understood as a certain internal structure (structure, organization), which develops objectively as a reflection of actually existing and developing social relations. It is not the result of the arbitrary discretion of the legislator, but a kind of cast from reality.

Challenges in enforcement proceedings: grounds and procedure.

Recusal consists in expressing no confidence in the subject of enforcement proceedings, whose objectivity and impartiality there are doubts, and demanding its further elimination.

1. Purpose laboratory work. 4

2. File system organization.. 4

3. Basic concepts and notations. 4

Storage device. 7

Catalog. 7

Route (file access path) 8

3. Basic commands Microsoft Windows. 9

3.1. Microsoft Windows prompt and general command format. 9

3.2. Directory maintenance commands. 12

3.3. Commands for working with files. 12

3.4. Drive maintenance commands. 13

3.5. Environment management commands. 15

4. I/O reassignment. Conveyors and filters.. 16

5. Command files.. 18

6. Laboratory work No. 7. 23

Operating room command language Microsoft systems Windows. 23

6.2. Requirements for the report. 23

6.3. Security questions.. 24

7. Laboratory work No. 8. 25

Batch files in the Microsoft Windows operating system. 25

7.1. Contents of the work.. 25

7.2. Requirements for the report. 25

7.3. Security questions.. 26

Appendix 1. Options for tasks for laboratory work No. 7. 28

1. Purpose of laboratory work

· studying the command line command system of the Microsoft Windows operating system;

· acquiring practical skills in creating multi-level directories and performing operations on files using the Microsoft Windows command line;

· study of the features of creation and practical use batch files in the Microsoft Windows operating system.

2. File system organization

3. Basic concepts and notations

The main unit of data storage on storage media (magnetic, laser, optical disks, flash cards, etc.) are files. File is a named collection of data that corresponds to a memory area on a storage medium. The files store programs ready for execution, source codes of programs, text documents, numerical data, graphic images and so on.

File names on the command line of the Microsoft Windows operating system are presented as:

<имя файла>::=<имя>[.<расширение>]

Filename restrictions vary greatly among file systems:

  • In FAT16 and FAT12, the file name size is limited to 8 characters (3 extension characters).
  • VFAT has a limit of 255 bytes.
  • In FAT32, HPFS file name is limited to 255 characters
  • In NTFS the name is limited to 255 Unicode characters
  • In ext2/ext3 the limit is 255 bytes.

In addition to file system limitations, operating system interfaces further limit the character set that is allowed when working with files.

ü For MS-DOS, only capital letters, numbers. Space, question mark, asterisk, greater than/less than symbols, and vertical bar symbol are not allowed. When calling system functions File names in lowercase or mixed case are converted to uppercase.

ü For Microsoft Windows, capital letters and lower case, numbers, some punctuation, space. Prohibited characters >< | ? * / \ : ".

ü For GNU/Linux (taking into account the possibility of masking), all characters are allowed except / and the zero byte.

Square brackets indicate that the element<extension> may be absent, i.e. is optional and optional. In this case, the point is not specified. Triangular brackets indicate that the parameter (in this case, the file name) is required to be entered, but is also optional.

Both Latin and Russian letters (uppercase and lowercase are the same) and numbers, as well as some special characters are allowed as characters used in file names:

~ ` ! @ # $ % & () _ " ^ { }

Some names on the Microsoft Windows command line are reserved to indicate special devices I/O and cannot be used as file names. These include:

CON console (keyboard and display)

NUL missing output (pseudo device - usually used

when debugging or to cancel display of work results)

PRN printer

AUX asynchronous interface

CLOCK$ clock driver

COM1 first serial interface

COM2 second serial interface

COM3 third serial interface

COM4 fourth serial interface

LPT1 first parallel interface

LPT2 second parallel interface

LPT3 third parallel interface

Examples of valid file names: 123, 2008_10_23.xls, mike.13, lab_7.pas, base

Operating system Microsoft Windows installed some standard extensions:

EXE (from the English Portable Executable; used in Microsoft Windows and some other systems)

COM (used in MS-DOS and Microsoft Windows);

Portable Executable (.exe; used on Microsoft Windows and some other systems)

BAT - for command files (see point 5).

In cases where you need to point to several files at once, the so-called file name template is used, containing special metacharacters (masks) “*” and “?”. These are special wildcard characters that serve the function of indicating a location in a file name.

A question mark inside a pattern indicates the presence of an arbitrary single character at a given position, and the "*" sign means that any characters can appear from this position to the end of the name or extension. For example:

*.exe - all files with the exe extension (bp.exe, test.exe, 9994567.exe, etc.);

a*.* - all files whose name begins with the letter “a’’ and the extension is any (algoritm.doc, a5.pas, act_1.doc);

file?.txt - all files with five-character names starting with the symbols file and having a txt extension (files.txt, file3.txt, file#.txt, but not file.txt, file54.txt).


Storage device

In Microsoft Windows to drives usually refer to storage media intended for recording and storing data and denoted by Latin letters followed by a colon:

A: , B: - for floppy drives magnetic disks; C: , D: , E: etc. - for hard drives, CDs, flash cards, and virtual disks. At each moment of its operation, the OS considers one of the drives to be current (working). After turning on the machine and loading Microsoft Windows, the current drive is the drive from which the boot was made (system drive). You can change the current drive by entering the name of the new drive in response to the Microsoft Windows command line prompt (see section 3.1).

Catalog(directory, folder) is a named collection of bytes on a storage medium containing the names of subdirectories and files. Microsoft Windows supports a multi-level directory structure. This means that inside any directory (in addition to files) you can place one or more lower-level directories (subdirectories). Each directory has its own directory containing information about all the files and subdirectories it contains.

Each disk has one main directory called root. It is created on the disk when it is formatted. For the FAT32 file system, the maximum number of elements in root directory now expanded to 65535. The root directory has no name and is indicated by the drive name with a backslash, for example: A:\, F:\

A directory that is part of another directory is subordinates. A directory that includes another directory is relative to it parental catalogue.

All directories, except the root directory, have names compiled according to the same rules as file names.

At each moment in time, the OS selects one from the entire set of directories of the current drive, called current(working) directory.

Route (file access path)

With a complex multi-level directory structure, to search for a file it is not enough to specify only its name. To accurately identify a file, it is also necessary to show its location in the structure in the form of a chain of names of sequentially subordinate directories. Such a chain is called route. The names of the directories that make up the route are separated by a \ character. For example: \SYS\EXE; TP\USER\PAS. If the route begins with a \ sign, then it starts from the root directory of the current drive and is called complete, if not, then from the current directory it is called incomplete. When describing a route, it is allowed to use special designation".." indicating a transition to the parent directory.

With the help of a route the concept " file specification":

<спецификация файла>::=[][<маpшpут>\]<имя файла>[.extension]

Where H:- drive name.

File specification - Full description file, including the drive and the directory in which it is located.

Examples of recording file specifications:

C:\Windows\tree.com

D:\TP55\USER\PAS\mg.pas

The first three examples indicate the complete route, the last two - incomplete.

When working with the Microsoft Windows file system, when referring to any file, you must specify the path to search for it (full or incomplete), with the exception of files in the current directory, as well as files located in directories specified in special Microsoft Windows command line commands: PATH And APPEND(see clause 3.5.).

3. Basic Microsoft Windows Commands

3.1. Microsoft Windows prompt and general command format

After successfully loading the Microsoft Windows operating system, the Microsoft Windows command line prompt appears, usually looking like:

C:\Documents and Settings\admin>

The presence of a prompt means that Microsoft Windows is ready to execute commands entered by the user from the keyboard. The invitation form can be changed for users using the PROMPT command (see section 3.5). The standard prompt includes the name of the current directory and the ">" sign, followed by a blinking cursor indicating the data entry position.

Rice. 1. Microsoft Windows command line session window, opened through the Start menu -> Programs -> Accessories -> Command Prompt

Rice. 2. Microsoft Windows command line session window opened via Start -> Run -> cmd

In response to the prompt, the user can execute any Microsoft Windows command or launch an application program presented in the form of a file with the COM, EXE or BAT extension. The information entered in response to the Microsoft Windows prompt is called command line. Only one command can be entered on one line, with the exception of special cases described in paragraph 4.

There are two types of Microsoft Windows commands: internal (built-in) and external. Built-in the commands are inside the command shell and they do not have separate executable files. External Microsoft Windows commands are presented as files on disk with the extension EXE, COM or BAT. As a rule, external Microsoft Windows commands are grouped together in one of the directories on the system drive (most often, but not necessarily, in the C:\Microsoft Windows\System32 directory). Method of execution external teams Microsoft Windows is no different from the way application programs are launched.

Commands are entered from the keyboard and have the following format:

[<маpшpут>\]<имя команды>[options]

The route is specified only for external Microsoft Windows commands and when calling application programs, if the corresponding files are not included in the current directory and if the corresponding routes were not specified in the PATH command (section 3.5).

Some commands require entering additional parameters indicating the objects on which the actions prescribed by the command are performed and the requirements for executing the command. The first parameter is separated from the command name by at least one space, just like parameters are separated from each other. For example:

C:\Microsoft Windows\tree.com /f

COPY A:\my.pas D:\TP\

aidstest A: /f /g /s /x

When running external commands and application programs, it is possible not to specify the file name extension (EXE, COM or BAT).

Below (clauses 3.1 - 3.5) is short description basic Microsoft Windows commands. The following notation is used to describe the commands: - storage device; - route;<Ф>, <Ф1>, <Ф2>... - file names or patterns;<СФ>, <СФ1>...- file specifications. Square brackets, as usual, indicate optional components.


3.2. Directory Maintenance Commands

DIR- viewing the directory directory.

Command format: DIR[<М>] [<Ф>]

Parameters: /p - paged output to the screen;

/w - display the table of contents line by line.

CD- change the current directory.

Command format: CD [<М>]

M.D.- creating a catalog.

Command format: MD<М>

R.D.- destruction of the directory.

Command format: RD<М>

Only an empty and non-current directory can be destroyed.

PATH- setting alternative routes for searching program files.

Command format: PATH[;][[<М1>] [;<М2>]... ]

The command tells the OS in which subdirectories to look for the file containing the executable program if it is not in the current directory (for EXE files, COM, BAT).

PATH (without parameters) - display a list of available directories;

PATH ; - cancel the installed list.

3.3. Commands for working with files

COPY- copying files.

Command format: COPY<СФ1> [<М>][<Ф2>]

Parameters:

<СФ1>- specification of the copied file or device;

<М>, <Ф2>- specification (directory, device) of the file copy;

/V - enable automatic verification of copying accuracy.


Features of using this command:

· it is possible to copy a group of files when using templates:

(COPY A:\*.* C:\WORK);

· if the second parameter is missing, copying is performed to the current directory;

· it is possible to merge files (merge):

COPYf1.txt + f2.txt f3.txt

· creation and input text file from the keyboard: COPY CON myfile.txt

(input is completed by pressing Ctrl+Z);

· output a file to a specified device:

COPY myfile.txt PRN

TYPE- output the file to the screen.

Command format: TYPE<СФ>

REN- renaming files.

Command format: REN<СФ1> <Ф2>

It is possible to rename a group of files using metacharacters:

RENB:\*.txt *.doc

DEL- destruction of files.

Command format: DEL<СФ>

Parameter: /p - issue a request to confirm destruction.

3.4. Drive maintenance commands

FORMAT- formatting (partitioning) of the disk (external command).

Command format: [M]FORMAT H:

Parameters: /s – copy system systems to the formatted disk Microsoft files Windows;

/f:n - definition of the type of disk to be formatted, where n=

DISKCOPY- physical copying of floppy disks.

Command format: DISKCOPY

It is possible to execute a command on one drive by changing floppy disks. Does not work if drives of different types are selected as drives H1: and H2:.

TREE- displaying a directory tree (external command).

Command format: [M]TREE [Н:]

Parameter: /f - adds file names to the list.

CHKDSK- checking the correctness of the data structure on floppy disks (external command).

Command format: CHKDSK[Н:][M][Ф]

Parameter: /f - sets the mode for correcting found errors.

The CHKDSK command detects orphaned clusters and corrupted subdirectory files. If the /F mode is set, these clusters or files are written to special files (filennnn.chk), where their contents can be viewed and corrupted files can be corrected with their help.

LABEL- setting the disc label.

Command format: LABEL[<метка диска>]

Parameter:<метка диска>- a string containing no more than 11 characters.

If the parameter is not specified, the current disc label is displayed and you are prompted to enter a new value.

The volume label can contain spaces and tabs. Do not use the following characters in the volume label:

* ? / \ | . , ; : + = () & ^ < > "

MS-DOS displays the volume label in uppercase letters. If the label is entered in lowercase, the LABEL command converts them to uppercase.

3.5. Environment management commands

PROMPT- installation of the Microsoft Windows command line invitation form.

Command format: PROMPT<текст пpиглашения>

Parameter:<текст пpиглашения>- any sequence of characters.

The text may include special characters that allow you to see in the invitation:

$n - name of the current drive;

$p - name of the current drive and directory;

$t - current time;

$d - The current date;

$g is the ">" symbol.

The standard prompt format is the PROMPT $p$g command.

DATE- setting the current date.

Command format: DATE[[<месяц>].[<день>].[<год>]]

If no parameters are specified, the current date is displayed and you are prompted to enter a new date.

TIME- setting the current time.

Command format: TIME [[<час>][:[<мин>][:[<сек>][,[<мсек>]]]]]

If the parameters are not specified, the screen displays current time and you are prompted to enter a new time value.

CLS- cleaning the screen.

Command format: CLS

VER- displays the version of the Microsoft Windows command line installed on the PC.

Command format: VER


4. I/O reassignment. conveyors and filters

Microsoft Windows allows redirect input and output data of any command (application program) that uses standard input/output means (keyboard, screen) by default to other physical devices (printer) or to a file. This means that the same program, without making any changes, can, in one case, enter data from the keyboard and output it to the display, in another case, enter data from a file and output it to the printer. For redirection, the symbols ">", ">>", " are used.<":

> - redirect output data:

DIR A:\labrab > labrab.txt

TYPE labrab.txt > PRN

>> - redirect output data with addition to an already existing file:

TREE C: > tree_all.txt

TREE D: >> tree_all.all

< - пеpеадpесовать входные данные:

DATE< filedate.txt

In addition to I/O redirection, Microsoft Windows provides a facility for using the output of one command as keyboard input for another command. For this purpose the so-called command pipelines, which are sequentially written commands separated by the "|" sign:

<команда1> | <команда2>

In this pipeline, the information output by the first command to the standard output device will be read by the second command without being displayed on the display screen.

Filters are special commands (programs) that convert data coming from the standard input stream (from the keyboard) and output the results of the conversion to the standard output stream (on the screen). The application of filters is based on the use of pipelines and I/O redirection. Microsoft Windows has three external commands that are filters: MORE, FIND and SORT.

MORE- page-by-page data output to the screen.

Command format: [M]MORE

Using the MORE filter, data is displayed on the screen until it is filled. When the screen is full, typing will stop and the message ''-- More --'' will appear on the bottom line. The next page will appear after pressing any key.

TYPE labrab.txt | MORE - page-by-page output of the text file myfile.txt;

DIR< MORE - постраничный вывод справочника текущего каталога.

FIND- search for file lines containing a specified sequence of characters.

Command format: [M]FIND "<текст>"

Options:<текст>- the desired sequence of characters;

/c - only count the number of lines in which the searched text is found;

/n - output lines in which the searched text is found, and their serial numbers;

/v - output lines in which the searched text is not found (exclusive search);

FIND "Operating system" ms_windows.txt - displays lines of the ms_windows.txt file that contain the words "Operating system" written in quotes;

DIR | FIND /c "04/01/2011" - displays the number of directory lines of the current directory containing the text "04/01/2011" (file creation date).

SORT- sorting (ordering) file lines by character codes.

Command format: [M]SORT

Parameters: /r - sort in descending order of the symbol code;

/+n - sorting position - the serial number of the character in the line by which sorting is performed.

If no parameters are specified, sorting is performed by the first character in ascending code order.

DIR | SORT /+37 - sorting the directory lines of the current directory by the 37th character (corresponds to the position of the first letter of the file name);

SORT< labrab.txt - сортировка строк файла labrab.txt по первому символу.

DIR | FIND ".2011" | SORT > dir_2011.txt - generates a file dir_2011.txt, including directory lines of the current directory containing information about files and directories created in 2011, sorted by name.

5. Batch files

Often during work there is a need to execute a certain sequence of commands, which must be repeated from time to time. To facilitate the work of users, it is possible to combine a sequence of commands into a package (from the English batch) and place it in a special batch file. Batch files- these are ordinary text files with the BAT extension and containing a sequence of lines, each of which is a Microsoft Windows command (or a program call) in the form in which they are typed on the keyboard for execution one by one.

The batch file is created as a regular text file using any text editor or the COPY CON command<имя файла>. The batch file is launched in the standard way via the command line.

In addition to regular Microsoft Windows commands, batch files also use special commands, such as ECHO, REM, PAUSE, GOTO, IF etc. All of them are built-in commands.

ECHO- message control command.

Command format: ECHO

The command is used to implement three functions:

1) ECHOON - enable the mode of displaying the names of executable commands on the screen;

2) ECHOOFF - cancel displaying the names of executable commands;

3) ECHO<сообщение>- display the text of the message on the screen (displayed regardless of the ECHOON/OFF state).

It is possible to output messages to a printer or to a file when using output redirection:

ECHO Hello! >PRN

It is possible to suppress the display of command text (including the ECHO command itself) by adding a symbol before the command @ :@ECHOOFF







2024 gtavrl.ru.