Learning bash commands in Linux OS. Recursive list and inode information

Bash - interpreter command language UNIX compatible systems. Executes commands from standard input (such as a terminal window) or from a file. Bash also includes useful extensions shells of the Korn and C languages ​​(ksh and csh commands, respectively)

Syntax

bash [options]

Options

-c string If this parameter is present, then the command will be read from the line string. If the command passed has additional arguments, they are considered positional and start at $0. (Chapter Arguments )
-i Interactive work of the interpreter
-l Watch INVOCATION below
-r Limitations in the operation of the shell. Watch RESTRICTED SHELL
-s If this parameter is specified and all required arguments are missing, they are read from standard input
-D List of all strings enclosed in double quotes with $ at the beginning are output to standard output. Required to complete the translation. No commands will be executed
[-+]0[shopt_option]

shopt_option - Extra options shells. Read the SHELL BUILTIN COMMANDS subsection. If this parameter is present6 then -0 in front of it sets specified parameter, and +0 cancels it. If shopt_option is not specified, +0 prints a list of set options to standard output in a format that can be reused as input.

-- Signals the end of parameter setting. Any parameters after it are treated as filenames and arguments to the script. The "-" option is equivalent to "--".

Bash also allows multi-character options. They must be described before single-character ones for their correct recognition.

--debugger Starts the debugger profile before running the script. Enables advanced debugging mode (more details in the description extdebug) and runs the trace function
(see parameter description -o).
--dump-po-string Equivalent to -D, but the output is in localizations.po file format
--dump-strings Completely similar to -D
--help Clue
--init-file file
--rcfile file If the interpreter is launched in interactive mode, it executes the initialization commands of the specified file file, and not from the standard initialization file ~/.bashrc.
--login Same as -l
--noediting
--noprofile Do not read system-wide configuration files when starting the interpreter shell /etc/profile and any local files settings such as ~/.bash_profile, ~/.bash_login or ~/.profile . By default, bash uses them when running in login mode (more details in the INVOCATION parameter).
--norc Do not read or execute the file personal settings~/.bashrc when running interactively. By default, this parameter is set when the shell is started with the command sh.
--posix Changing bash's default behavior when encountering a command other than POSIX standard(to ensure compatibility)
--restricted Shell actions are limited (read below about the RESTRICTED SHELL parameter)
--verbose Same as -v (verbose output)
--version Print information about the current version of the interpreter to standard output

Arguments

If, after processing the parameters, there are still arguments not associated with the -c or -s parameters, then the first argument is considered to be the name of the file containing the script with the commands. $0 is the file name and the remaining arguments are written positionally. Bash reads the script's commands, executes them, and then exits. The exit status will be equal to the exit status of the last script command executed. If no commands were executed, the return value will be "0". First, an attempt is made to open the script from the current folder; if it is not there, the specified file will be searched according to PATH variable for scripts.

bash call

login shell- if the first character after -- is 0 or the launch was performed with the -login parameter.

interactive shell -interactive work. If launched without arguments and without the -c parameter with the standard input/output device in the form terminal.app or launched with the -i parameter.

Processing initialization files. If any of the initialization parameter files exist but cannot be read, bash on Mac reports an error.

When bash is started in interactive or login mode, the commands from the file are read and executed first /etc/profile (if available), then the presence of files is checked ~/.bash_profile , ~/.bash_login , and ~/.profile and if they are available and accessible, then the commands from them are executed in the same order as they are listed. To skip the processing of the above files, you can use the parameter --noprofile

If bash was started in login mode, the file is checked and, if present, executed ~/.bash_logout .

If launched in interactive mode, without login mode, then during startup the file is additionally executed~/.bashrc . To disable this file, use the parameter --norc or --rcfile file to replace the executable file with another ( file).

When bash is started in normal mode, for example, to execute a script, it looks at the global environment variable BASH_ENV and uses its value to find the executable file.

When bash is called by the command sh it tries to use the oldest version to ensure compatibility with the POSIX standard. When called in interactive mode or in --login mode, the files are read and executed sequentially first/etc/profile And ~/.profile , to prohibit the use of these files, use the parameter --noprofile. It also interactively reads the value of the ENV variable to use as a path to find the executable file. When run with sh, the --rcfile startup option is ignored and cannot be used. When starting in standard mode no configuration files are used, the interpreter operates in POSIX mode.

When bash is running in posix mode using the parameter in command line --posix the interpreter will adhere to the POSIX standard for initialization files. In this case, interactive mode uses the value of the ENV variable, which must contain the name of the initialization file; no other initialization files will be executed.

Bash is a command shell or, in other words, a command interpreter that is used by default in most Linux distributions. The Bash shell has a lot of capabilities. More than just an interpreter, in the right hands Bash can become a full-fledged programming language.

The shell's main job is to execute commands, but in addition to utilities located on the file system, Bash has its own set of commands, many of which you use every day without realizing it. These Bash commands are not on disk, but are built into the shell itself. In this article we will look at basic commands bash on linux, which may be useful in some situations.

This article will not have a very long introduction and we will get straight to the point. All list elements are arranged in random order. After going through all of them, you will have a better understanding of working in Bash.

1. source

This command allows you to read and execute all commands from the specified file in the current command shell. This means that all environment variables set in it will be visible in all scripts or commands that you execute. Let me remind you that if you run a regular script and declare a variable in it, then it will be available only to it because a separate instance of the shell is created for scripts. It inherits the parent's variables, but not vice versa. This command is often used to update the environment after chroot:

source /etc/profile

2. alias

The alias command allows you to create aliases for other commands. For example, you can configure it to run sudo apt update && sudo apt upgrade when you type update. If you call the command without parameters, it will display a list of already defined aliases. See more details about how to create in a separate article.

3.bind

With this command you can associate a keystroke with a specific command or function. For example, let's configure the pwd command to be executed when pressing F12 in a terminal window:

bind ""\e, ~, (, )) to search for files using name patterns.

  • Substitutes variables that can be used by the shell.
  • Redirects the output of one command as input to another command using a pipe.
  • Performs command merging.
  • Executes the command if it is a built-in interpreter command, or starts a process if the command is external.
  • Redirects standard I/O.
  • To complete three latest features need to use special operators. Let's look at all the listed functions.

    2.1. Nicknames

    Command aliases are designed to allow shell commands to be entered more efficiently. By means of an alias, a command of almost any complexity can be replaced by an arbitrary string. To view the list of aliases and, if necessary, add to it new nickname, you should use the alias command.

    For example:

    $ export HELLO="Hello from environment! " # space must be escaped with quotes

    Environment Variables

    An environment is a set of variables whose values ​​can change the behavior of the shell.

    When the shell starts running, it sets several environment variables for itself. Their names are standard. Programs and scripts can ask for their values ​​instead of trying to figure out the information they need on their own.

    In this way, the command interpreter determines the environment variables that are used in the current session. Each new command entered is actually launched as a child process of the parent process, as which, in in this case The bash command interpreter is used. Environment variables differ from regular variables in that they are accessible to both parent and child processes. Automatic detection of environment variables occurs after user authentication in the system. The login program, if the authentication process is successfully completed, determines, based on the /etc/passwd file, which command interpreter will be used in the user's session. After defining command interpreter The session is configured according to the configuration files presented below.

    Configuration fileDescription
    /etc/profile

    Defines environment variables for all users on the system. This file is executed at the first login and contains basic environment variables, such as the PATH command location search variable, the HOSTNAME host name variable, and the HISTSIZE command history size variable. In addition, this file generates additional environment variables from configuration files located in the /etc/profile.d directory.

    /etc/bashrc

    Executed for all users, every time the command is launched bash interpreter. IN this file The value of the PS1 variable is determined, as well as additional command aliases (alias). An alias is a shortened, arbitrarily defined name of a command or sequence of commands that allows you to execute complex sequences of commands without entering them from the keyboard, but by calling them by calling the corresponding alias. Variables defined in this file can be reassigned by a similar user-defined file -/.bashrc, which has higher priority.

    -/.bashprofile

    Used as a file containing individual settings user. Executes only once when the user logs in. In addition, this file runs the file -/.bashrc

    ~/.bashrc

    This file contains environment variables and aliases set by the user. It is executed every time the user logs in or when a new bash session is opened. This file is best suited for defining user variables and aliases.

    ~/.bash_logout

    This file is executed every time you log out or end the last session of the bash interpreter. By default, this file contains a command to clear the terminal screen.

    /etc/inputrc

    This file contains a description of the interpretation of various key combinations, and also contains special key combinations, pressing which causes the execution of specified commands.

    Environment variables are quite convenient way storing information that is frequently used within the current session of working with the system. If necessary, the user can create almost any environment variables (try not to change the values ​​of environment variables already in use) and read their values ​​throughout the entire time he works with the command shell. To create a temporary environment variable, you must enter its name and assign the appropriate value to it. For example,

    export AB=/usr/dog/contagious/ringbearer/grind

    IN in this example The temporary environment variable AB is assigned the path to a directory located quite “deep” in the file system directory hierarchy. The export command indicates the need to export the value of the AB variable to a shell in order to make it available to other shells that may be open within the current session with the system. Now the above directory can be reached by executing the command cd $AB

    The only drawback of temporary environment variables is that they are automatically destroyed when the current session with the system ends. In order to create a permanent (as opposed to temporary) environment variable, it must be added to the shell configuration file.bashrc.

    To change the /etc/profile and /etc/bashrc configuration files, you must be root.

    Regular users can modify the ~/.bash_profile, ~/.bashrc and ~/.bash_Iogout configuration files located in their home directories. These configuration files can be configured to set your environment variables using the export command and can be used in any session.

    One of the most frequently changed environment variables is the PATH variable. You can also override or extend the PATH environment variable in the ~/.bashrc configuration file.

    in this example, the PATH variable will contain its current value plus the home directory as the search path for executable files.

    For these changes to be applied in the environment of the current shell, you must run the command source .bashrc

    The most common shell environment variables are:

    • BASH - Contains the full path to the bash command (typically /bin/bash).
    • BASH_VERSION - Bash version number.
    • DIRSTACK - An array containing the current directory stack value.
    • EDITOR- text editor default.
    • EUID - Numeric Effective Identifier current user.
    • FUNCNAME - name current function in the script.
    • GROUPS - An array containing a list of groups to which the current user belongs.
    • HISTFILE - The location of the command history file. Typically, command history is stored in the ~/.bash_history file.
    • HISTFILESIZE - The number of command lines that can be stored in the history file. After this number is reached, new command lines are entered into history by deleting the oldest command lines. By default, the size of the list of recently used commands is 1000 lines.
    • HOME - User's home directory.
    • HOSTNAME - The name of this computer (node).
    • HOSTTYPE - Computer type.
    • LANG - Current default language.
    • LC_CTYPE is an internal variable that determines the character encoding.
    • MAIL - Mailbox file locations Email user. Typically, this is a file located in the /var/spool/mail directory whose name is the same as the user's login name.
    • MAILCHECK - Interval in minutes between mail checks.
    • OLDPWD - The directory that was current until the directory was last modified.
    • OSTYPE - Current operating system.
    • PATH - A colon-separated list of directories in which to search for executable files. The order in which directory names are searched is extremely important. When executing commands, the directories listed in this variable are checked sequentially from left to right. Thus, when executing the foo command located in the /bin and /usr/bin directories, the command located in the /bin directory will be executed. To run the foo command located in the /usr/bin directory in a similar situation, you must either specify the full path to this command or change the order of the directory names in the PATH environment variable. The current search directory must be specified explicitly ("."); the shell does not search the current directory by default. Searching for startup programs in the current directory is potentially dangerous due to the possibility of unintentional execution dangerous program, so the PATH variable is usually initialized without the "." To add the path to your own commands or shell scripts to the PATH variable, you should place them in the /bin subdirectory of your home directory, which will automatically be added to the PATH variable. Not all executable commands are located in the directories listed in the PATH environment variable. Some commands are built directly into the shell. Other commands can be redefined using aliases, allowing commands with parameters of virtually any complexity (in terms of syntax) to be replaced with one simple name. In addition, it is possible to create functions that store a whole sequence of commands.
    • PPID - The identification number of the process corresponding to the command that launched the current shell (for example, the process that created the shell).
    • PS1, PS2, PS3, PS4 - Variables that determine the type of shell prompt.

      The PS1 and PS2 variables set the primary and secondary shell prompts.

      A secondary prompt (PS2) appears if you press the Enter key without syntactically finishing entering a command.

      This variable contains a minor prompt that occurs when multi-line text editing or incomplete command entry. By default it is denoted as >.

      PS3. This variable contains the prompt that is present in the select statement used to organize interactive console menus. By default, the PS3 prompt in the select statement is #?.

      PS4. This variable is used primarily when debugging shell scripts and by default contains string value «++».

      For example, running the command to get DNS information:

      # nslookup >

    • PWD - User's current working directory. This value changes each time you change to a different directory using the cd command.
    • SECONDS - script running time (in seconds).
    • SHELL - Current command interpreter.
    • SHELLOPTS - List of enabled interpreter options.
    • SHLVL - Number of times new copies of the command interpreter are launched.
    • UID - Numeric identifier of the current user.
    • USER - Current user name.
    • $# - The total number of parameters passed to the script.
    • $* - All arguments are not passed to the script (output to a line).
    • $@ - Same as the previous one, but the parameters are displayed in a column.
    • $! - PID of the last process running in the background.
    • $$ - PID of the script itself.

    To view the values ​​of all variables in the current session, both those you define and those in the environment, issue the set command with no parameters or env printenv .

    You can remove a variable with the unset command.

    2.4. Substitutions and organization of interaction between commands

    Substituting environment variable values current session with the system can be accomplished by using the dollar sign ($) metacharacter. As a result, the shell automatically replaces the variable's name with its value. For example,

    Substituting the result of an arithmetic expression

    There are two syntactic forms for substituting the result of an arithmetic expression: $[expression] and $((expression)). For example,

    echo "I am $ years old."

    Command Substitution

    Command substitution allows you to use the output of one command on a command line that contains another command. Two alternative substitution formats can be used: $(command) or `command` (single backquotes). For example,

    Expanding the tilde character

    The tilde character (~) allows you to quickly enter directory names.

    ~ The name of the user's home directory ~/subdirectory The name of one of the subdirectories in the user's home directory ~+ The name of the current directory ~- The name of the previous directory

    Expanding curly braces

    Using curly braces, you can enter one command instead of several of the same type. The parentheses must contain a list, the elements of which must be separated by commas. The interpreter reads the elements one by one and forms a separate command with each of them, which it then executes. For example, the command

    mkdir expenses/(Jan,Feb,Mar) is equivalent to mkdir expenses/Jan mkdir expenses/Feb mkdir expenses/Mar

    Channels

    The channel metacharacter (|) indicates the need to organize interaction between commands by using the result of the execution (output) of another command as input data (input) of a command. In other words, using a pipe (pipeline), the results of the first command can be passed as input to the second command. For example,

    cat /etc/passwd | sort | head -3

    Sequences and groups of commands

    Using command sequences and groups allows you to enter multiple commands on one line.

    command1;command2 Execute command 1 first, then command 2 (command1;command2) Run separate copy interpreter in which to execute commands 1 and 2 sequentially ( command1;command2) Execute commands 1 and 2 sequentially in the current interpreter command1 && command2 Execute command 2 only if command 1 is successfully executed command1 || command2 Execute command 2 only if command 1 fails

    The result of any command execution (that is, the result of the termination of the corresponding process) is the exit code. Successful completion has code 0, unsuccessful completion code 1. Is the completion code value assigned to a predefined variable? (question mark). For example, echo $?

    Re-executing commands

    The shell has facilities that allow you to recall previous commands and edit them. Shell command history is a list of previously used commands. This list can be viewed using the history command.

    After you enter a command line, the shell places it in the command history. A list of previously used commands is stored in a file, which allows you to call any desired command line from it at any time for re-execution. After calling the command line again, it can be edited. Command history is stored in the .bash_history file, which is located in the user's home directory. By default, the command shell can "remember" up to 1000 command lines.

    To view a list of previously used commands, run the history command.

    It can be used either without parameters or with a parameter that allows you to specify the number of commands to be displayed. Each command line has its own number in the command history.

    History expansion syntax: !n Execute the given command number!! Execute previous command!string Execute the most recent command starting with the given string!?string? Execute the most recent command containing the given string Instead of directly executing the command line contained in the command history, you can call it for later editing. Use the cursor keys"up arrow" and "down arrow" For step by step viewing

    command history and selecting the required command line.

    3. Bash built-ins

    A list of bash shell built-ins can be obtained using the help command or found on the man page in the SHELL BUILTIN COMMANDS section.

    • Here are some useful built-in commands:
    • enable - Causes the shell to execute an executable file of the same name instead of a builtin command. Useful if you have your own script named like echo.
    • eval [arguments] - Constructs a command on the fly from the specified arguments and sends it for execution.
    • let - Evaluate expressions.
    • - Read and execute commands contained in the file. Used to define user variables. and functions.
    • basename - Highlight a local name.
    • expr - Expression evaluation.
    • read - Enter the value of a variable.
    • shift - Shift the list of parameters.
    • test - Test the condition.
    Other built-in commands serve as instructions in the bash command language.

    Moscow State Institute of Electronic Technology

    (Technical University)

    Department of Integrated Electronics and Microsystems

    LABORATORY PRACTICUM

    BY COURSE:

    OPERATING SYSTEMLINUX

    Compiled by: assistant department. IEMS Kozlov A.V.

    Moscow, 2007

    The laboratory workshop is intended primarily for masters of engineering and technology studying in the first year Synopsys program in the direction 210100.68, to master the Red Hat Enterprise Linux (RHEL) 4.0 operating system. It is also designed for FreeScale students and all users with entry-level or no Linux experience who want to learn team environment Linux and its main applications that the user requires when working with computer-aided design systems.

    This workshop consists of eight laboratory works that allow the user to effectively master the commands of the command interpreter, as well as gradually learn to write files - Shell, Gawk, Perl and Tcl scripts. Each laboratory work includes the following sections: title, task and purpose of the work; theoretical information with test questions; example of laboratory work; procedure for performing laboratory work; laboratory task and work report form. The syntax for writing commands in the shell, along with options, parameters, actions, expressions, and object paths, is designed for the BASH command environment. A list of references is provided at the end of the laboratory workshop.

    MOSCOW STATE INSTITUTE OF ELECTRONIC ENGINEERING (TECHNICAL UNIVERSITY)

    LABORATORY WORK No. 1

    IN THE COURSE “LINUX OPERATING SYSTEM”

    Learning bash commands on Linux

    DESCRIPTION COMPLETED:

    KOZLOV A.V.

    MOSCOW 2007

    Laboratory work No. 1 Studying bash commands on Linux

    Goal of the work : using the BASH command interpreter, master the skills of working with commands in the Red Hat Enterprise Linux 4.0 operating system.

    Duration of work – 4 hours

    Theoretical information

    operating system Linux was originally developed as a free, flexible, feature-rich, multi-user, high-performance platform designed to serve and solve the problems of scientists around the world. Due to the “scientific focus”, such a platform initially did not have an extended graphical interface, which is widely used when solving home problems - computer games, the Internet, interactive programs for connecting users, as well as when solving office problems - working with database systems, plotting graphs and histograms. Often, the work of scientists with the Linux operating system was reduced simply to the usual interaction of the user (a person working on a computer) with the console (a terminal window on the monitor screen with text information). To understand commands entered by the user in Linux, command interpreters have been developed, which are translators of commands understandable to humans into control signals understandable to the operating system kernel. The main task of the operating system is to mediate the transmission of commands from a person to a computer. And, despite the fact that today the Linux operating system is used everywhere not only in institutes, Design centers, computer centers, but also for home and office purposes, consoles (terminal windows) are still widely used, and to many they seem even more convenient compared to working with the mouse and icons (icons in Linux) in a graphical environment.

    Command interpreter is a string interactive interface with a command line prompt between the user and the operating system. The user enters commands on the command line, the command interpreter “accepts” them and sends them as instructions to operating system for execution. The command interpreter allows you not only to enter commands, but also to redirect command line input and output, and to perform operations in the background, allowing the user to do other tasks at the same time.

    Many command interpreters have been developed for Linux: Bourne Again shell (BASH), Public Domain shell (PDKSH), TCSH interpreter and Z-shell. Although BASH is the default interpreter, you can use any other environment. For the convenience of everyday work, only one command interpreter is enough. Red Hal Linux includes all the major shells, but the BASH shell is installed and used by default. This means that this operating system uses BASH to work at the command line unless otherwise specified.

    Command line. The Linux command line interface consists of a single line where commands with options and parameters are entered. In the BASH shell, the beginning of the command line is usually marked invitation in the form of a dollar sign ($); Other Linux shells may use a different form of prompt. Once prompted, the user can enter either a single command or a command with options and parameters. If the user does not have enough size for the command prompt, then it is possible to limit it with the “/” character. The command is entered from the keyboard and entered using the key. For example, to output system date and system time the user can use the command date .

    $date

    Fri Jun 8 15:42:35 MSD 2007

    Or, for example, to display a calendar with the current month, use the cal command.

    $cal

    July 2007

    Su Mo Tu We Th Fr Sa

    1 2 3 4 5 6 7

    8 9 10 11 12 13 14

    15 16 17 18 19 20 21

    22 23 24 25 26 27 28

    29 30 31

    The main shell interface is a command line interface that interprets entered commands and sends them to the system. Commands entered at the command line must follow certain syntax rules. The general rule for entering commands is: the first word entered on the command line should be the name of the command; The following words are the command options and parameters. Each word on the command line is separated from other words by one or more spaces or tabs.

    Option - is a single or multi-letter code preceded by a hyphen that modifies the type of action performed by the command. As an example of a command with options, we give the command ls . When used without options, this command produces a list of all files and directories contained in the current directory. Apart from file names with and without extensions, there is nothing else in this list. For example, when you enter the command ls with option - l team ls produces line-by-line output of information for each file, namely its size, date and time of last modification. In the following example, the user enters the command ls with option - l. A hyphen before an option is required. This is how the Linux system distinguishes an option from a parameter.

    $ ls -l

    total 28

    The -a option allows you to display all files in the current directory, including the so-called hidden files. Configuration files are often hidden. Hidden file names always begin with a dot, which is why they are often called chiseledfiles. In most cases, the options are combined. In this case, one common hyphen is placed before the group of options. For example, the -al option displays information about all files contained in the current directory, including hidden files. The new ttt file is displayed.

    $ ls -al

    total 40

    Parameter is the word that is entered on the command line after options. File management commands typically use file names as parameters. For example, if you only need information about one file, gauss.plx, specify its name after the -l option:

    $ ls -l gauss.plx

    The user's work begins in the BASH shell environment, which is loaded by default. It has special command line editing capabilities that can be very useful when learning the Linux OS. Before executing commands, you can edit them by moving the cursor across the command line and inserting or deleting characters. This is especially useful when working with very complex teams. Editing operations will help correct an error when typing a command. Using the |up| You can display the command you just executed. You can then run the command again or, after editing it, run the modified command. This feature is very convenient when repeating certain operations multiple times, for example, when editing one and the same file.

    The purpose of the command interpreter is to work with files: creating, copying, renaming, moving, deleting and modifying data. Even if the user does not directly work with the console, but uses graphical applications, these file operations occur independently of him.

    Creation of files and directories. In Linux, file and directory are two types of data, so they are created using different commands. To create a directory (directory, folder), use the command reserved in Linux mkdir (“make directory” - create a directory). In the following example, we will create a directory new in the current directory. To do this, use the mkdir command and the name of the directory new, separated by a space.

    $ mkdir new

    The directory has been created. However, sometimes you need to create an entire nested structure, when inside an already created folder there should be another one, and inside it another one, and so on. For these purposes, the attachment option –p is used as part of the mkdir command. The following example uses one command to create subfolders: first folder 1, inside it folder 2, and inside it folder 3.

    $ mkdir -p 1/2/3

    You can create files either using commands or using built-in and external Linux text editors, such as kedit, nedit, gedit, and so on. However, the listed editors require the operation of a graphical shell, which means the operation of the graphics system. If you don't have it, you can, for example, use a text editor VIM or analogues that do not require the operation of the graphics system. You can also create files using text file managers such as Midnight Commander (mc command). The user (designer) often needs text files keep text information, which accompanies the process of calculating an integrated circuit or, for example, the electrical parameters of a simulated semiconductor device. It is also necessary to process (delete, add, sort, split) the received data. Such actions are also carried out using Linux commands. One of the simplest commands for creating a text file is the command cat.

    The cat command does not have its own interface, so after entering the cat command with a redirection symbol (see below) and the name of the new file, you can immediately write text information by moving from line to line using the Enter key. Exiting the cat editor (filter) is done using the Ctrl-D key combination. Below is an example of creating a file using the cat command.

    $ cat > new _ file

    The resulting file is viewed using the cat command and the file name separated by a space.

    $ cat new _ file

    Or, for example, saving text information from the console when the command runs ls with the -a option to file r, you can use the data redirection function (see below) and the command tee with the -a option.

    $ ls -l | tee-a r

    Copying files and directories. Copying files and directories is carried out using the cp command, after which the copy object is indicated with relative or absolute paths, separated by a space, and the new destination of the copy of this object, separated by a space. The following example copies the file gauss.plx from the current directory to subdirectory 1, which is located in the current directory.

    $ cp gauss . plx 1

    If you have access rights to Linux objects (lab. work No. 2), you can also copy this file to user Alex, whose working directory has the following absolute path /home/alex, using the following command.

    $ cp gauss . plx / home / alex

    If a file with the same name already exists at the destination when copying a file, it will be overwritten. This may result in loss of required data. To avoid this, use the cp command with the –i option, and Linux will ask the user each time if he really wants to overwrite the file. The new kind The last command looks like this.

    $ cp -i gauss.plx /home/alex

    Directories are copied in the same way as files. However, when copying directories with files and subdirectories, the –R option is used as part of the cp command. Being in the /home/antonk/111 directory, copy the laba2 directory to a higher level, i.e. to the /home/antonk directory. Two dots indicate a hierarchy level one step higher.

    $ cp - R laba 2 ..

    Renaming and moving files and directories. Renaming files and directories is carried out using the mv command, after which the object to be renamed is indicated, separated by a space, and the new name of the object, separated by a space. Renaming directories occurs in the same way as files. Let's rename the file gauss.plx to a new file called gauss2.plx. If a file with the same name as the new name of the renamed file already exists in this directory, it will be overwritten with the contents of the renamed file. To prevent this, also use the –i option. By the way, on Linux the use of extensions is not required. They are used only for file association and executable programs.

    $ mv –i gauss.plx gauss2.plx

    Deleting files and directories. Removing files and directories in Linux is done using the rm command, where the names of the files to be deleted are indicated, separated by a space. !!! Be careful when working with this command, you may delete the necessary data. Similar to the cp command, use the –i option in conjunction with the rm command. A command with this option will ask for confirmation to delete each file and directory. In the following example we will delete the file gauss 2. plx , requesting confirmation for deletion .

    rm –i gauss2.plx

    Wildcards. Sometimes when working with the command interpreter you need to find or match files using a pattern. For example, you know only the first letter of a file name and want to find all files in the working directory that begin with that letter. Or you know a sequence of several letters in a file name or extension and you need to find it among several hundred other files. In this case, you need to use Linux special characters. The command interpreter uses a series special characters, called wildcards, that can be used to search for files, match them, and create a list of file names. These characters are the asterisk, question mark, and square brackets (*, ?, ). Having received a partial file name, the command interpreter uses these characters as a template to search and generate a list of names of the detected files. A parameter with an unqualified file name is replaced with a list of matching file names. This list of names can be used as a parameter in commands that operate on multiple files (for example, ls). The command interpreter wildcards are listed in Table. 1.

    Table 1. Shell special characters

    Common symbols

    Purpose

    Separating commands on one command line

    "team"

    Executing a command

    Comparison with the class of possible characters in file names

    Designates the next character as special.

    Used to indicate control characters

    Piping the standard output of one command as input for another command

    Running a command in the background

    Command for working with a list of previously entered commands

    Wildcards

    Result of application

    Matches any character set in file names

    Matches any single character in file names

    Redirection symbols

    Result of application

    The exclamation mark causes the file to be overwritten if it exists. This symbol overrides the option that prevents existing files from being overwritten

    Redirects standard input from a file or device to a program

    Redirects standard output to a file or device, appending the output to the end of the file

    Matches any single character in file names

    Result of applying standard error message output

    Redirects and appends standard error output to a file or device

    Redirects standard error output to standard input

    Redirects standard error output to a file or device

    Pipes standard error output to another command's input

    For example, the asterisk (*) character can be used to refer to files whose names begin or end with a specific combination of characters. The example shows how to use the asterisk (*) character in any combination of characters.

    $ls

    docl doc2 document docs mydoc monday tuesday

    Displayed a complete list of files in the working directory.

    $ ls doc*

    docl doc2 document docs

    This example showed how we used the asterisk character to “filter out” file names that do not start with the letter combination “doc”. Only file names that contain the combination “doc” are displayed. In this case, the remaining files are not deleted; they are simply not displayed to the user.

    $ ls *day

    monday t uesday

    Here we have displayed file names that end with the combination “day”.

    $ ls [ mt ] * d *

    monday tuesday

    And here we have displayed the names of files whose first character is the letter “m” or “t”, the subsequent characters are arbitrary, then the letter “d” and again arbitrary characters.

    Be careful when using an asterisk in conjunction with the rm command - it may result in loss of your data. The following command deletes all contents of the current folder.

    rm *

    $ ls *day

    docl doc2 docs

    The question mark (?) denotes only one unspecified character in file names.

    After reading this article, you will find out what it is bash(standard Linux command interpreter), learn how to use standard commands: ls, cp, mv...understand the purpose of inodes, hard and symbolic links, and much more.

    This tutorial is intended for those new to Linux and for those who want to review or improve their understanding of basic Linux principles, such as copying and moving files, creating links, using standard Linux commands along with redirections and pipes. In this article you will find many examples that explain the material presented. For beginners, most of the information will be new, but for more advanced users this material can be an excellent tool for summarizing existing knowledge and skills.

    Introduction to bash

    Shell

    If you use Linux, then you know that after logging in you are greeted by a command interpreter prompt. For example this:

    \$

    If after login it loads graphical shell, then to get to the command interpreter you need to launch a terminal emulator (gnome-terminal, xfce4-terminal, konsole, xterm, rxvt...) or switch to one of the virtual terminals by clicking CtrlAltF1 or CtrlAltF2 etc.

    The shell prompt on your computer may differ from what is shown in the example. It may contain the username, computer name, and the name of the current working directory. But despite all these differences, the program that prints this invitation is called " shell"(shell), and most likely your command shell is a program called bash.

    Are you running bash?

    You can check if bash is running with the following command:

    \$ echo \$SHELL/bin/bash

    If you receive an error as a result of executing this command or its output differs from that in the example, then it is possible that your system does not use bash as the command shell. Despite this, most of the material will be relevant, but we still recommend that you switch to bash. This can be done (if bash is installed on the system) with the command:

    \$ bash

    What is bash

    Bash (an acronym for " B ourne- a gain SH ell") is standard interpreter commands on most Linux systems. His responsibilities include processing and executing commands with which the user controls the computer. Once you are done, you can exit the shell process. After pressing the keys CtrlD, teams exit or logout The shell process will be terminated and you will be prompted to enter your username and password again.

    Using "cd"

    Let's start using bash to navigate the file system. To get started, type the following command:

    $ cd/

    With this command we indicated to bash that we want to move to the root directory - / . All directories in the system are organized in a tree structure and / this is its beginning (or root). Team CD serves to change the current working directory.

    Paths

    To find out where in the file system in this moment you are in (current working directory) type:

    \$ pwd /

    In the above example / - command argument CD- called path. This is the location on the file system where we want to move. In this case / - absolute path, this means that the path is relative to the root directory.

    Absolute paths

    Here are some examples of absolute paths

    /dev /usr /usr/bin /usr/local/bin

    As you may have already noticed, all these paths have in common that they start with / . By specifying the path /usr/local/bin as an argument to the command CD we tell her to go to the root directory / , then to the usr directory, then to local and bin. Absolute paths always start with /

    Relative paths

    The second type of path is called relative. Bash, team CD and other commands count these paths relative to the current directory. Relative paths never start with / . For example, if we are in /usr

    \$ cd /usr

    Then we can go to /usr/local/bin using the relative path

    \$ cd local/bin \$ pwd/usr/local/bin

    Usage ".."

    Relative paths can contain one or more directories «..» . ".." indicates the parent directory of our working directory. Example:

    \$ pwd/usr/local/bin\$ cd.. \$ pwd/usr/local

    As you can see, the team cd..‘raises us to a higher level’.

    Can add .. To relative path. This will allow us to move to a directory that is at the same level as the one we are in. Example:

    \$ pwd/usr/local\$ cd ../share \$ pwd/usr/share

    Examples using relative paths

    Relative paths can be quite tricky. Here are some examples. The result of executing the commands is not shown, try to determine which directory you will be in using bash.

    \$ cd /bin \$ cd ../usr/share/zoneinfo \$ cd /usr/X11R6/bin \$ cd ../lib/X11 \$ cd /usr/bin \$ cd ../bin/../bin

    Working directory "."

    Before we finish talking about the team CD, there are a few more things worth mentioning. Firstly, there is another special directory «.» , which points to the current directory. This directory is used to run executable files located in the current directory.

    \$ ./myprog

    In the last example myprog is executable file located in the current directory, which will be launched for execution.

    cd and user's home directory

    In order to go to home directory, you need to dial

    \$ CD

    Without an argument, cd will move you to your home directory. For the superuser, the home directory is usually /root, and for ordinary users- /home/username/. But what if we want to indicate specific file, located in the home directory. For example, as an argument to the program 'myprog'? You can write:

    \$ ./myprog /home/user/myfile.txt

    However, use absolute paths access to files is not always convenient. The same operation can be done using ~ –tildes:

    \$ ./myprog ~/myfile.txt

    ~ - a special name that points to the user's home directory in bash.

    Other users' home directories

    But what if we need to point to a file in another user's home directory? To do this, after the tilde you need to indicate the name of this user. For example, to point to the file fredsfile.txt located in user fred's home directory:

    \$ ./myprog ~fred/fredsfile.txt

    Linux commands

    Introduction to ls

    You are probably already familiar with the team ls, which, called without arguments, displays a list of files stored in the working directory:

    \$ cd /usr \$ ls X11R6 doc i686-pc-linux-gnu lib man sbin ssl bin gentoo-x86 include libexec portage share tmp distfiles i686-linux info local portage.old src

    If you specify the option -a, you will be able to see all files, including hidden ones (whose names begin with a dot).

    \$ ls -a. bin gentoo-x86 include libexec portage share tmp .. distfiles i686-linux info local portage.old src X11R6 doc i686-pc-linux-gnu lib man sbin ssl

    Detailed list of directories

    After the command itself ls one or more files or directories can be specified as its argument. If you specify a file name, the command ls will display information only about this file. And if you specify the directory name, ls will show all its contents. Option '-l' teams ls can be very useful if you want to know more than file names detailed information about them (permissions to the file, owner name, time of last modification of the file and its size).

    The following example shows the use of the option '-l' to display information about files stored in the /usr directory

    \$ ls -l /usr drwxr-xr-x 7 root root 168 Nov 24 14:02 X11R6 drwxr-xr-x 2 root root 14576 Dec 27 08:56 bin drwxr-xr-x 2 root root 8856 Dec 26 12:47 distfiles lrwxrwxrwx 1 root root 9 Dec 22 20:57 doc -> share/doc drwxr-xr-x 62 root root 1856 Dec 27 15:54 gentoo-x86 drwxr-xr-x 4 root root 152 Dec 12 23:10 i686-linux drwxr-xr-x 4 root root 96 Nov 24 13:17 i686-pc-linux-gnu drwxr-xr-x 54 root root 5992 Dec 24 22:30 include lrwxrwxrwx 1 root root 10 Dec 22 20:57 info -> share/info drwxr-xr -x 28 root root 13552 Dec 26 00:31 lib drwxr-xr-x 3 root root 72 Nov 25 00:34 libexec drwxr-xr-x 8 root root 240 Dec 22 20:57 local lrwxrwxrwx 1 root root 9 Dec 22 20 :57 man -> share/man lrwxrwxrwx 1 root root 11 Dec 8 07:59 portage -> gentoo-x86/ drwxr-xr-x 60 root root 1864 Dec 8 07:55 portage.old drwxr-xr-x 3 root root 3096 Dec 22 20:57 sbin drwxr-xr-x 46 root root 1144 Dec 24 15:32 share drwxr-xr-x 8 root root 328 Dec 26 00:07 src drwxr-xr-x 6 root root 176 Nov 24 14: 25 ssl lrwxrwxrwx 1 root root 10 Dec 22 20:57 tmp -> ../var/tmp

    The first column shows information about the access rights of each file in the list. (A little later I will explain which letter means what) The next column shows the number of links to each element of the list. The third and fourth columns are the owner and group of the file, respectively. The fifth column is size. The sixth is the time the file was last modified (‘last modified time’ or mtime). The last column is the name of the file or directory (If this is a link, then after the ‘ –> ‘ stands for the name of the object it refers to).

    How to view only directories

    Sometimes there is a need to view information only about directories, and not about all their contents. The option will help you cope with this task '-d', which tells the command to display information about directories only. Example:

    \$ ls -dl /usr /usr/bin /usr/X11R6/bin ../share drwxr-xr-x 4 root root 96 Dec 18 18:17 ../share drwxr-xr-x 17 root root 576 Dec 24 09:03 /usr drwxr-xr-x 2 root root 3192 Dec 26 12:52 /usr /X11R6/bin drwxr-xr-x 2 root root 14576 Dec 27 08:56 /usr/bin

    Recursive list and inode information

    Option action '-R' the opposite of action '-d'. It allows you to display information about files located in a directory recursively. The contents of the directory are shown first top level, then the contents of all subdirectories in turn, and so on. The output of this command can be quite lengthy, so we're not providing an example, but you can try it yourself by typing ' ls -R' or ' ls -Rl‘.

    And finally, the option '-i' used to print the inodes of each file system object.

    \$ ls -i /usr 1409 X11R6 314258 i686-linux 43090 libexec 13394 sbin 1417 bin 1513 i686-pc-linux-gnu 5120 local 13408 share 8316 distfiles 1517 include 776 man 23779 src 43 doc 1386 info 92 portage 36737 ssl 70744 gentoo-x86 1585 lib 5132 portage.old 784 tmp

    What are inodes?

    Each file system object (file, directory...) has its own unique number, called inode(inode number). This information may seem insignificant, but understanding the function of inodes will help you understand many file system operations. For example, let's look at «.» And «..» like the links present in each directory. To understand what a directory is «..» , find out the inode of the directory /use/local

    \$ ls -id /usr/local 5120 /usr/local

    As we can see, the inode of the directory /usr/local is 5120. Now let’s see what inode the directory /usr/local/bin/.. has:

    \$ ls -id /usr/local/bin/.. 5120 /usr/local/bin/..

    It turns out that the inodes of the /usr/local and /usr/local/bin/.. directories are the same! This means that inode 5120 is referenced by two names: /usr/local and /usr/local/bin/.. That is, these are two different names one directory. Each inode points to a specific location on the disk.

    Each inode can have multiple filesystem object names associated with it. The number of file 'synonyms' (file system objects that reference the same inode) is shown by the number in the second column of the ' command output ls -l‘.

    \$ ls -dl /usr/local drwxr-xr-x 8 root root 240 Dec 22 20:57 /usr/local

    In this example you can see (second column) that the /usr/local directory is referenced by 8 different file system objects. Here are their names:

    /usr/local /usr/local/. /usr/local/bin/.. /usr/local/games/.. /usr/local/lib/.. /usr/local/sbin/.. /usr/local/share/.. /usr/local/ src/..

    mkdir

    Let's look at the command mkdir. It is used to create new directories. The following example demonstrates the creation of three new directories (tic, tac, toe) in the /tmp directory

    \$ cd /tmp $ mkdir tic tac toe

    Default command mkdir cannot create a nested directory structure. Therefore, if you need to create several nested directories ( won/der/ful), then you will have to call this command three times in turn:

    \$ mkdir won/der/ful mkdir: cannot create directory "won/der/ful": No such file or directory \$ mkdir won \$ mkdir won/der \$ mkdir won/der/ful

    You can simplify this operation by adding the option '-p' to the mkdir command. This option allows you to create a nested directory structure:

    \$ mkdir -p easy/as/pie

    To learn more about the capabilities of this utility, read the help, which is called by the command man mkdir. There is help for almost all the commands in this manual (for example man ls), except CD, because it is built into bash (for such commands, help is called like this: help cd)

    touch

    Let's move on to studying commands cp And mv, used to copy, rename and move files and directories. But before that, let's create an empty file in the /tmp directory using the command touch:

    \$ cd /tmp \$ touch copyme

    Team touch updates the last access time of the file (sixth column of the command output ls -l) if it already exists or creates a new empty file if it does not exist yet. After this operation we should have an empty file /tmp/copyme.

    echo

    Now that we have an empty file, let's write into it text string using the command echo, which prints the argument passed to it to the standard output device (a text terminal in our case).

    \$ echo "firstfile" firstfile

    To write a line to our file, let's redirect the command output to it echo:

    \$ echo "firstfile" > copyme

    Sign > (more) tells the shell to redirect the output of the command on the left to the file whose name is on the right. If a file with the same name does not exist, it will be created automatically. And if such a file already exists, it will be overwritten (all its contents will be erased before writing our line). Team 'ls -l' will show that the size of our file is now 10 bytes - nine bytes are occupied by the word 'firstfile' and one byte by the line feed character.

    \$ ls -l copyme-rw-r--r-- 1 root root 10 Dec 28 14:13 copyme

    cat and cp

    To output the contents of a file to the terminal, use the command cat:

    \$ cat copyme firstfile

    Now we can begin to analyze the basic functionality of the command cp. This command takes two arguments. The first one is already a name existing file('copyme'), the second is the name of the new copy we want to make ('copiedme').

    \$ cp copyme copiedme

    We can make sure that the new copy of the file has a different inode number (this means that we actually received a new separate file, and not just a link to the old one)

    \$ ls -i copyme copiedme 648284 copiedme 650704 copyme

    mv

    Now let's use the command mv to rename the file (“copiedme” –> “movedme”). The inode number does not change after this operation, only the file name changes.

    \$ mv copiedme movedme \$ ls -i movedme 648284 movedme

    The inode number does not change only on the condition that the renamed file remains within the file system where it was located original file. We will take a closer look at the design of file systems in one of the following parts of this tutorial.

    Team mv allows you not only to rename files, but also to move them. For example, to move a file /var/tmp/myfile.txt to the directory /home/user you need to give the command:

    \$ mv /var/tmp/myfile.txt /home/user

    The file will be moved to the user's home directory user even if it is located on a different file system (in this case, the file will be copied to a new location after which the original will be deleted). As you might have guessed, moving a file to another file system changes its inode. This happens because each file system has its own separate set of inodes.

    It should be noted that there is a possibility that the new assigned inode number may coincide with the old one, but it is extremely small.

    To move several files simultaneously into one directory you need to write:

    \$ mv /var/tmp/myfile1.txt /var/tmp/myfile2.txt /home/user \$ mv -t /home/user /var/tmp/myfile1.txt /var/tmp/myfile2.txt

    If you add the option '-v', a report on the operation performed will be displayed on the screen:

    \$ mv -vt /home/user /var/tmp/myfile1.txt /var/tmp/myfile2.txt"/var/tmp/myfile1.txt" -> "/home/user/myfile1.txt" "/var/tmp/myfile2.txt" -> "/home/user/myfile2.txt"