To work in Ubuntu user can choose one of two possible interface options: graphical or interface command line. GUI(GUI - Graphical user interface) is familiar to most users, in which you need to use various desktop elements to perform actions. It has its advantages, which are expressed mainly in the convenient and familiar format for presenting information, as well as in the absence of the need to know any commands.

However, many Linux users prefer to work in command line(CLI, Command Line Interface). Typically, these users will be involved in some way with programming or system administration, however, knowledge of the basics of bash will be useful for all users. The command line allows you to execute commands much faster than using the GUI, while saving resources. Moreover, commands often have no analogues in the graphical interface and, thanks to this, give users significant freedom in their actions. At the same time, the command line interface is built into the operating system kernel, which means it is available even when you cannot use the graphical shell. The commands themselves are the same for all operating systems. Linux based, be it Ubuntu, CentOs, Fedora or any other.

What is bash

Bash stands for Bourne again shell, a name partly borrowed from an earlier version of the UNIX shell, which was simply called the Bourne shell (after the name of its developer, Stephen Bourne).

Bash allows you to interact interactively with your computer by entering specific commands and receiving the appropriate response. This command processor also allows you to execute scripts (commands from a file), can autocomplete file and directory names, and allows the use of variables, branching and looping operators.
Further in the article we will present the simplest and most necessary commands for working in bash, which will help you get your bearings and start using the command line for your tasks yourself, but first you need to go to the command line interface.

Login to the command line

Using Ubuntu as your operating system, you can access the command line in two ways, namely through the console or through the terminal.
If you want to enter the command line through the terminal, then to do this you need to press Ctrl+Alt+F(1-6) - depending on the selected number (F1, F2...) you will be taken to the first, second or other virtual console ( they are independent and run when Ubuntu boots), each of which has a command line interface. If you press Ctrl+Alt+F7, you will go to the seventh virtual console, which has GUI.

As for the terminal, it is a graphical program that emulates a console. You can find it in the menu by selecting Applications, then Accessories, and then Terminal, or by pressing the keyboard shortcut Ctrl+Alt+T. You will be able to execute commands while still being in the GUI.
It is also possible that you need to connect to a server on which Ubuntu is installed. In this case you need to use special program(for example, puTTy): Enter the desired IP address, and then enter the username and password.

Note.
When you enter your password into the command line, it is not displayed - you just need to type the password and press Enter. If the password is entered correctly, you will be able to continue working at the command prompt.

User and system

Using bash you can easily get whatever you need technical information about users and the system.
If you want to identify under which user you are logged in this moment, you need to enter the following command into the command line:

If you need to find out not only about yours, but also about other users currently on this operating system, use the commands:

Unlike whoami, these commands show more detailed information: in addition to the username, you will also find out what terminal line is being used, the start time of the session, the IP address and some other data.

As for system data, you can view it using the uname command. By itself, this command will not give you much information - only the name of the system. However, if you use the keys, you can learn much more.

Keys- these are special arguments that are written separated by a space after the command and begin with one or two hyphens. They define the parameters that will be applied to the command. Typically, you can find out about available keys by writing a command followed by --help (or -help): for example,

For the uname command, you can specify the -a (or --all) switch, and then all information about the operating system will be displayed on the screen:

If you are interested specifically in kernel data, then type the following command:

In this case, you will learn about the release and version of the operating system kernel.
You can get information about all processes using this command:

And the pstree command will display information in the form of a process tree.

You can find out the network name of a machine using the hostname command.

Navigating directories

In this section, you will be introduced to basic bash commands that will allow you to perform the most simple steps on the command line.
The cd command allows you to move from one directory to another. Moreover, if you use a command without switches, you will end up in your home directory; in order to go to a specific directory, you just need to write down its path, for example:

Cd /home/users/dir1

You can also specify the cd command with specific options:

cd ../.. - move up two directories;

cd - - go to the previous directory (in which you were before moving to the current one).

The pwd command will indicate the path of the directory in which you are currently located.

Create, move and delete

Use the mkdir command to create a directory. Don't forget to include a name:

A new directory will be created in the directory where you are currently located, but you can also enter some other path to create a new directory:

Mkdir /home/users/dir1

To create a file, you need to enter the touch command and the name of the future file:

In this case, it is also possible to specify the path where you need to create the file:

Touch /home/users/dir1/file1

To move directories and files, use the mv command, after which you write the name of the directory or file you want to move, and then the location where you want to move it:

Mv file2 /home/users/dir2 mv dir1 /home/users/dir3

Note that the mv command is also used for renaming, so if there is no dir2 directory, you would write a command like this:

then the dir1 directory will be renamed to the dir2 directory. This example also applies to files that you can give different names using the mv command.

To delete files you should use the rm command, and to delete directories rmdir. If you want to remove a directory, use the rm command with the -rf switches:

Rm -rf /home/users/

Another action you can use is copy using the cp command. The syntax for this command is the same as the previous ones - you simply write what you want to copy and where. To copy a directory, you must use the -r switch, and if the final directory (dir2) does not exist, it will be created during copying:

Cp -r dir1 dir2

Information about files, directories and processes

To display information about the contents of a directory, use the ls command. If you use it without keys, it will simply display information about the files and directories in a given (or specified) directory. The main switches that are often used with this command are:

A - you will be shown all the files in the directory, including those that start with. (dots);

S - request information about the sizes of files (or directories);

L - data about files, in particular the name of the user who created them, access rights and creation time;

H - conversion of file sizes into an easy-to-read format (KB, MB, etc.).

Keys can also be combined, so the usual command to display the size of the content is:

Another team that will help you get necessary information, is the du command. For example, by entering this command:

you will receive information about file sizes and names.

You can get information about running processes using the df command. It is best to use it immediately with the -h switch so that the data is shown in a more readable format:

Finding and Using Regular Expressions

To search for files in bash, use the find command. Its syntax is as follows: find + desired directory (path) + key (or several) + key criteria + (optional) subsequent action on the found files.

You can familiarize yourself with many of the keys of this command, which greatly facilitate and narrow the search, by entering into the command line:

For example, the following command will allow you to find all files that are located in the dir1 directory and are named file:

Find /home/users/dir1 -name ‘file*’

For searching, it is most convenient to use some regular expressions, namely:

* - denotes any number of characters, including their absence (for example, the request file* will find all files: file, file1, file829, fileabc, etc.);

Indicates one character (the request file? will find files with one character after the word file: file1, file9, filea, etc.; the request file?? will find files with two characters: file12, file34, file92, etc. .);

Denotes a subset of values ​​that one character can take (the query file will find files: file1, file2, file3 and so on up to file9; the query file files filea, fileb, filec and filed).

Redirection and pipeline

Redirection of the output of a command is specified by the symbol > or >>. The difference is that when using > the output of the command will be written over the contents of the file, and when using >> the output will be appended to the end of the file.

This is very convenient to use for logging if you want to write some data to a file. For example, this command will write all files found according to the specified parameters to log file(it will automatically appear in the directory you are working in):

Find /home/users -name ‘file*’ >> log

As for the pipeline, this tool allows you to use the output of one command as the input of another command. To do this you need to use the | symbol:

Find /home/users -name ‘file*’ | sort -r

If you enter this line, then all files that match the condition will first be found, and then with the sort command they will be sorted in reverse order (due to the use of the -r switch).

File Contents

If you want to see the contents of a file, you can use the cat command - in response to the command you will see everything that is contained in the file. If there is too much data, use the pipeline and the more command - it will allow you to view the content page by page:

Cat file1 | more

If you need to not only view the contents of a file, but also edit it, then you need to use one of the utilities: nano or vim. These are text editors with which you can open a file, edit it, and save it. Despite the apparent similarity, these utilities have a number of differences; Most users agree that nano is a simpler editor, while vim has more capabilities.

You can find the Russian documentation for nano at this link: http://help.ubuntu.ru/wiki/nano

And vim documentation is available in this section: http://help.ubuntu.ru/wiki/vim

Conclusion

There are many different commands and switches that can be used in bash. In this article, we focused only on the most basic, basic commands with which you can perform operations and obtain the necessary information.

Full Russian-language documentation can be found at this address:

  1. && . Strictly speaking, this is not a team. If you want to execute several commands at once, put a double ampersand between them like this: first_command && second_command. The terminal will execute the commands in order. You can enter as many commands as you like.
  2. alias Assigns names you create to long commands that you can't remember. Enter the alias long_command short_command.
  3. cd. Changes the current terminal folder. When you start the terminal, it uses your home folder. Enter cd folder_address, and the terminal will work with the files that are located there.
  4. clear. Clears the terminal window of all messages.
  5. history. Displays all the commands you have recently entered. Additionally, you can switch between recent commands using the Up and Down keys. If you do not want the command you entered to be written down, put a space in front of it like this: your_command.
  6. man. Displays a guide to programs and commands. Type man package_name or man your_command.
  7. whatis. Displays short description any program. Enter the command and the program name whatis package_name.

To perform many actions on the system, such as installing and uninstalling programs, you will need administrator rights, or the superuser root as it is called in Linux.

  1. sudo This command will give you superuser rights. Type sudo before the command you want (for example, sudo apt upgrade) to run it as an administrator. The system will ask you for your password.
  2. sudo su . After this command, all commands you enter will be executed as the superuser until you close the terminal. Use it if you need to run a lot of commands with administrator rights.
  3. sudo gksudo . Command to run a GUI application with administrator rights. For example, if you want to move or change system files, type sudo gksudo nautilus (indicate the file manager you use).
  4. sudo!! . This command will run the previously entered command with administrator rights. Useful if you typed the command without sudo .

Do not execute commands as superuser that you do not understand.

Installing and uninstalling applications in Linux is performed by package managers. In Ubuntu the package manager is called apt, in Fedora - dnf, in Arch and Manjaro - pacman. They download applications from online repositories, package sources. Commands should be given to them with superuser rights.

apt (Debian/Ubuntu/Mint)

  1. sudo apt install package_name. Install the required package.
  2. sudo apt-add-repository repository_address. Add a third-party repository.
  3. sudo apt update . Update package information.
  4. sudo apt upgrade . Update all packages to the latest (perform after apt update).
  5. sudo apt remove package_name. Remove unnecessary package.
  6. sudo apt purge package_name. Remove an unnecessary package with all dependencies if you want to free up more space.
  7. sudo apt autoremove . Remove all unnecessary dependencies, orphan packages and other garbage.

dnf (Red Hat/Fedora/CentOS)

  1. sudo dnf install package_name. Install the required package.
  2. sudo dnf config-manager --add-repo repository_address. Add a third-party repository.
  3. sudo dnf upgrade . Update all packages to the latest ones.
  4. sudo dnf remove package_name. Remove unnecessary package.
  5. sudo dnf autoremove . Remove all unnecessary dependencies.

pacman (Arch/Manjaro)

  1. sudo pacman -S package_name. Install the required package.
  2. sudo yaourt -S package_name. Install a package from AUR if it is not in the main repository.
  3. sudo pacman -Sy . Update package information.
  4. sudo pacman -Syu . Update all packages to the latest ones.
  5. sudo pacman -R package_name. Remove unnecessary package.
  6. sudo pacman -Rs package_name. Remove an unnecessary package with all dependencies.

You can install and remove several packages at once by simply listing them separated by a space.

sudo apt install firefox clementine vlc

If you want to install a package but don't know its exact name, type the first few letters of the package name and press Tab twice. The package manager will show all packages whose names start with the same name.

  1. kill. This command is used to forcefully terminate processes. You need to enter kill PID_process. The PID of a process can be found by typing top .
  2. xkill. Another command to end processes. Enter it, then click on the window you want to close.
  3. killall. Kills processes with a specific name. For example, killall firefox.
  4. top. Displays a list of running processes, sorted depending on CPU resource consumption. A kind of terminal “System Monitor”.

Viewing and editing files

  1. cat. When the command is used with a single text file (like this: cat file_path), it displays its contents in a terminal window. If you specify two and more files, cat path_to_file_1 path_to_file_2 , it will glue them together. If you enter cat file_path_1 > new_file, it will merge the contents of the specified files into new file.
  2. chmod. Allows you to change file permissions. Can be useful if you want to make changes to a system file.
  3. chown. Changes the owner of a file. Must be executed with superuser rights.
  4. file. Displays information about the specified file.
  5. nano . Opens a simple text editor. You can create a new one text file or open an existing one: nano path_to_file.
  6. rename. Renames a file or several files. The command can also be used for files by mask.
  7. touch. Changes the date last discovery or modification of the specified file.
  8. wget. Downloads files from the Internet into a terminal folder.
  9. zip. Unpacks and compresses archives.

Creating and deleting files and folders

  1. mkdir. Creates new folder in the current terminal folder or in the specified folder: mkdir folder_path.
  2. rmdir. Deletes the specified folder.
  3. rm. Deletes files. Can delete as separate file, and a group corresponding to certain characteristics.

Copying and moving files

  1. cp. Creates a copy of the specified file in the terminal folder: cp path_to_file. Or you can specify the destination cp path_to_file path_to_copy.
  2. mv. Moves a file from one folder to another. You can specify a name for the file to be moved. Funnily enough, in Linux this command can also be used to rename files. Just specify the same folder where the file is located and a different name.

Search files

  1. find . Search files by specific criteria, such as name, type, size, owner, creation and modification date.
  2. grep. Search for text files containing specific strings. The criteria are very flexible.
  3. locate. Searches for files and folders whose names match your query and displays their paths in file system.

  1. lsblk. This command shows you what drives you have on your system and what partitions they are divided into. The command also displays the names of your partitions and drives, in the format sda1, sda2 and so on.
  2. mount Mounts drives, devices, or file systems so you can work with them. Typically, devices will connect automatically as soon as you click on them in the file manager. But sometimes you may need to mount something manually. You can connect anything: disks, external drives, partitions and even ISO images. This command must be executed with superuser rights. To mount an existing disk or partition, enter mount sdX .
  3. umount. Dismounts file systems. The umount sdX command will mount the file system external media so you can extract it.
  4. dd. This command copies and converts files and partitions. It has many different uses. For example, dd if=/dev/sda of=/dev/sdb will make an exact copy of the sda ​​partition on the sdb partition. dd if=/dev/zero of=/dev/sdX will erase the contents of the specified media with zeros so that the information cannot be recovered. And dd if=~/Downloads/ubuntu.iso of=/dev/sdX bs=4M will make bootable media from the distribution image you downloaded.

Linux Commands for User Management

  1. useradd. Registers a new user. Enter useradd username and the user will be created.
  2. userdel. Deletes the user's account and files.
  3. usermod. Changes a user account. May move the user's home folder or set a date for the account to be locked.
  4. passwd. Changes passwords accounts. A regular user can only change the password for his own account; a superuser can change the password for any account.

Linux Commands for Network Management

  1. ip. Multifunctional team to work with the network. The ip address show command displays information about network addresses, ip route controls routing, and so on. By issuing the commands ip link set ethX up, ip link set ethX down, you can turn connections on and off. The ip command has many uses, so it's best to read the manual before using it, or type ip --help
  2. ping. Shows whether you are connected to the network and helps determine the quality of the connection.

And one more thing

Finally, the main Linux commands. They put a cow on the screen that can talk to you (don't ask what the developers use).

  1. cowsay anything. The cow will say what you tell it.
  2. fortune | cowsay. The cow will give out a smart (or not so smart) thought or quote.
  3. cowsay -l . Lists all animals that can be displayed in the terminal. In case you don't like cows.
  4. fortune | cowsay -f animal_from_list. The animal of your choice begins to spout quotes, sometimes relevant ones.
  5. sudo apt-get install fortunes fortune-mod fortunes-min fortunes-ru . Will force the entire zoo to speak Russian. Without this, animals quote Twain and Wilde.

These are not all Linux commands. If you need to know in detail the parameters and how to use Linux commands, you can use the built-in tutorial. Type man your_command or your_command --help .

In this article we will look at the basic Linux commands that will be useful for beginners in mastering this operating system.

What is Linux?

Linux is the operating system kernel. You may have heard of UNIX. Well, Linux is a clone of UNIX. It was created by Linus Torvalds of Scratch. Linux is free and open source - you can simply change anything in Linux and redistribute it under your own name! There are several Linux-based builds, commonly called distributions.

  • Ubuntu Linux
  • Red Hat Enterprise Linux
  • Linux Mint
  • Debian
  • Fedora

Linux is mainly used on servers. About 90% of the Internet runs on Linux servers and here's why.

Linux is free, but the main problem with using Windows servers is their cost. Linux is fast: The OS that runs about 80% of the world's smartphones, Android, is also made from the Linux kernel. Linux is safe and most of the viruses in the world run on Windows.

Linux Shell or "Terminal"

Linux Shell is a program that receives commands from the user and passes them to the OS for processing and displays the output. Shell Linux is its main part. Most distributions come with a graphical user interface (GUI), but mostly server-based Linux uses a CLI (command line interface).

In this tutorial, we will look at the basic commands that we use in the Linux shell.

To open a terminal, click Ctrl + Alt + T in Ubuntu or click Alt+F2, type gnome-terminal and press enter. On the Raspberry Pi, enter lxterminal.

Linux Commands

Basic commands

1.pwd- when you first open a terminal, you are taken to your user's home directory. To find out which directory you are in, you can use the "pwd" command. This command displays the full path from the root directory to the current working directory: in the context in which (by default) the entered commands will be executed. The root is the basis of the Linux file system. Indicated by a slash (/). The user directory usually looks like "/home/username".

Result of pwd command in linux

2.ls- use the "ls" command to find out what files are in the directory you are in. You can see everything hidden files using the command "ls -a".


result of ls command in linux

3. cd- use the "cd" command to change to a directory. For example, if you are in your home folder and want to go to your downloads folder, you can type " CD Downloads" Remember that this command is case sensitive and you must enter the folder name exactly as it is. But there is one caveat. Imagine you have a folder named "Raspberry Pi". In this case, when you enter " cd Raspberry Pi", the shell will accept the second argument of the command as something else, so you will get an error message saying that the directory does not exist. Here you can use a backslash, i.e.: " cd Raspberry\ Pi" Spaces work like this: if you just type " CD” and press enter, you will be taken to your home directory. To go back from a folder to a previous folder, you can type "cd..". Two dots return to the previous directory.

result of cd command in linux

4. mkdir and rmdir- use the mkdir command when you need to create a folder or directory. For example, if you want to create a directory called "DIY", you can enter " mkdir DIY" Remember, as already said, if you want to create a directory named "DIY Hacking", you can enter " mkdir DIY\ Hacking" Use rmdir to remove a directory. But rmdir can only be used to delete an empty directory. To remove a directory containing files, use the rm command.

result of mkdir and rmdir command in linux

5.rm- use the rm command to remove files and directories. Use "rm -r" to remove only the directory. It deletes both the folder and the files it contains when using only the rm command.


result of rm command in linux

6.touch- The touch command is used to create a file. This could be anything from an empty txt file to an empty zip file. For example, " touch new.txt».

result of touch command in linux

7. man And --help- To learn more about the command and how to use it, use the man command. Shows the command's help pages. For example, " man ls" shows the man pages for the ls command. Typing the command name and argument helps show how the command can be used (for example, cd --help).


result of cd --help command in linux

8.cp- use the cp command to copy files via the command line. It takes two arguments: the first is the location of the file to be copied, the second is where to copy.

result of cp command in linux

9.mv- use mv command to move files via command line. We can also use the mv command to rename a file. For example, if we want to rename the file "text" to "new", we can use " mv text new" It takes two arguments, just like the cp command.

result of mv command in linux

10.locate- The locate command is used to locate a file on a Linux system, just like the search command on Windows. This command is useful when you don't know where the file is saved or the actual file name. Using the -i argument with the command helps ignore case (it doesn't matter if it's uppercase or lowercase). So, if you want a file with the word "hello", it gives a list of all the files on your Linux system that contain the word "hello" when you type "locate -i hello". If you remember two words, you can separate them with an asterisk (*). For example, to find a file containing the words "hello" and "this", you can use the command "locate -i * hello * this".

Intermediate commands

1. echo- The "echo" command helps us move some data, usually text, into a file. For example, if you want to create a new text file or add to an already created text file, you just need to enter “echo hello, my name is hich >> new.txt.” You don't need to separate spaces with a backslash here because we enclose in two triangle brackets when we end what we need to write.

2. cat- Use the cat command to display the contents of a file. Typically used for convenient viewing of programs.

result of echo command in linux

3. nano, vi, jed- nano and vi are already installed text editors on the Linux command line. The nano command is a good text editor that colors keywords and can recognize most languages. And vi is simpler than nano. You can create a new file or change a file using this editor. For example, if you need to create a new file called "check.txt", you can create it using the "nano check.txt" command. You can save your files after editing using the sequence Ctrl + X then Y (or N for no). In my experience, using nano to edit HTML doesn't look very good due to its color, so I recommend jed text editor. We'll start installing packages soon.

4. sudo- A widely used command in the Linux command line, sudo stands for "SuperUser Do". So if you want any command to be executed as an administrator or root, you can use the sudo command. For example, if you want to edit a file such as viz. alsa-base.conf which requires root privileges, you can use the command - sudo nano alsa-base.conf. You can enter the root command prompt using the "sudo bash" command and then enter your user password. You can also use the "su" command, but before that you need to set the root password. To do this, you can use the command "sudo passwd" (not misspelled, it's passwd). Then enter New Password root.

5.df- use the df command to see the available disk space on each partition of your system. You can simply type df on the command line and see each mounted partition and its used/available space in % and in kilobytes. If you want it to be displayed in megabytes, you can use the "df -m" command.


result of df -m command in linux

6.du- Use du to find out how a file is used on your system. If you want to know the disk space size of a specific folder or file in Linux, you can enter the df command and the name of the folder or file. For example, if you want to know the amount of disk space used by the documents folder in Linux, you can use the "du Documents" command. You can also use the "ls -lah" command to view the sizes of all files in a folder.

7. tar- Use tar to work with tarballs (or files compressed in a tarball archive) on the Linux command line. It has a long list of uses. It can be used to compress and decompress various types of archives tar, such as .tar, .tar.gz, .tar.bz2 etc. It works based on the arguments given to it. Eg, " tar -cvf" for creating .tar archive, - xvf to unpack the .tar archive, - tvf to view the contents of the archive, etc.

8. zip, unzip- use zip to compress files into a zip archive and unzip to extract files from a zip archive.

9.uname- use uname to show information about the system your Linux distribution is running on. Using the "uname -a" command displays most information about the system: kernel release date, version, processor type, etc.

result of uname -a command in linux

10.apt-get- use apt to work with packages on the Linux command line. Use apt-get to install packages. This command requires root privileges, so use the sudo command with it. For example, if you want to install the text editor jed (as I mentioned earlier), we can enter the command “sudo apt-get install jed”. Likewise, any packages can be installed as follows. It is recommended to update your repository every time you try to install a new package. You can do this by typing "sudo apt-get update". You can upgrade your system by typing "sudo apt-get upgrade". We can also upgrade the distribution by typing "sudo apt-get dist-upgrade". The "apt-cache search" command is used to search for a package. If you want to search for it, you can type "apt-cache search jed" (this does not require root).


11.chmod- use chmod to make a file executable and change the permissions granted to it in Linux. Imagine you have Python code on your computer called numbers.py. You will need to run "python numbers.py" every time you need to run it. Instead, when you make it executable, you just need to run "numbers.py" in a terminal to run the file. To make the file executable, you can use the command "chmod + x numbers.py" in this case. You can use "chmod 755 numbers.py" to give it root permissions, or "sudo chmod + x numbers.py" for the executable root file. Here's a little more.

12.hostname- Use the command hostname to find out your name on your host or network. Basically, it displays your hostname and IP address. Simply typing "hostname" will give you the hostname. By typing “hostname -I” you will get your IP address on the network.

13.ping- use ping to test your connection to the server. Wikipedia says: "Ping is an administrative utility computer network, used to test the availability of a host on an Internet Protocol (IP) network.” For example, when you type, " ping google.com", it checks if it can connect to the server and get back. It measures this round trip time and gives you detailed information about it. You can also use this command to check your Internet connection. If it pings the Google server (in this case) - the Internet connection is active!


ping command result in linux
  • You can use the command clear to clear the terminal if there are too many commands accumulated there.
  • TAB can be used to fill in the terminal. For example, you just need to type "cd Doc" and then TAB, and the terminal fills in the rest and makes it "cd Documents".
  • Ctrl+C can be used to safely stop any command in the terminal. If Crtl+C did not work, then you can use Ctrl+Z to stop a process running in the terminal.
  • You can exit the terminal using the command exit.
    You can shut down or restart your computer using the commands sudo halt And sudo reboot.

Alekseev Igor Gennadievich,

Brantsevich Petr Yulyanovich

OPERATING SYSTEMS and SYSTEM PROGRAMMING

educational and methodological manual for students of the specialty

"Software information technologies»


UDC 004.04 (075.8)

BBK 32.973 i 73

Reviewer:

A47 Alekseev I.G. Educational and methodological manual Operating systems and system programming: for students. specialist. “Information technology software”/I.G. Alekseev, P.Yu. Brantsevich - Mn.: BSUIR, 2009. - 73 p.

ISBN 985-444-No.

The manual covers the basic commands of the UNIX operating system, designed to work with files and directories, as well as to create processes and organize interaction between them. The structure of laboratory work for the course "OSiSP" is given.

UDC 004.04 (075.8)

BBK 32.973 i 73

ISBN 985-444-387-6© Alekseev I.G., Brantsevich P.Yu 2009

© BSUIR, 2009


1. BASIC UNIX OS COMMANDS.................................................... ............. 4

2. Laboratory work.................................................... ........................ 7

Laboratory work No. 1 Working in UNIX/Linux OS,

BASH interpreter ................................................... ............................................... 7

Laboratory work No. 2 Working with files and directories of the UNIX OS.... 12

Laboratory work No. 3 Processes in UNIX/Linux OS .................................. 17

Laboratory work No. 4 Using signals in UNIX/Linux OS ..... 21

Laboratory work No. 5 Using channels in UNIX/Linux OS...... 26

Laboratory work No. 6 Threads in UNIX/Linux OS……………………… 33

Laboratory work No. 7 Semaphores in UNIX/Linux OS…………………… 36

Lab #8 Using shared memory in

UNIX/Linux OS………………………………………………………………… 39

Literature................................................. ................................................... 42


BASIC UNIX OS COMMANDS

Operating system OS Linux created based on OS UNIX and has a largely similar structure and command system. The user can work in text mode using the command line, or using a graphical interface X Window and one of the desktop managers (for example, KDE or GNOME ). Moreover, 7 users can work in the system simultaneously (6 in text console mode and 1 in graphical mode), switching between users is carried out by pressing keys:



.

In table 1 shows the main system commands

Table 1

Team Arguments/Keys Example Description
dir catalog dir /home
ls -all and others (see man) ls -all Prints the contents of a directory to the console
ps -a -x and others (see man) ps -a
mkdir directory name mkdir stud11 Creates a directory
rmdir directory name rmdir stud11 Removes a directory
rm file rm myfile1 Deletes a file
mv file new name mv myfile1 myf1 Renaming a file
cat file cat 1.txt Outputting a file to the console
CD directory name cd home Browse through catalogs
grep (see man) grep "^a" "words.txt" Finding a string in a file
kill process pid kill 12045 Kills a process
top Prints a list of processes to the console
htop Outputs to the console full list running processes
su Switching to root mode
chmod file permissions chmod 777 1.txt Changing file permissions
mount device directory mount /dev/cdrom/MyCD Mounting devices
dd if=file of= file bs=n count=n dd if=/dev/hda1 of=/F.bin bs=512 count=1 Byte-by-byte copying
ln file1 file2 -l ln file1 file2 ln –l file1 file2 Create a hard or symbolic link to a file
uname -a uname –a System Information
find dir file find /home –name a1.txt Search files
man man fgetc System Help
info info fgetc System Help

Linux and Windows use different file systems to store and access information on disks. Linux uses file systems - Ext2/Ext3 ,RaiserFS, FFS and others. All file systems are supported logging . Journaled The file system first writes the changes it will make to a separate part of the file system ( magazine ) and only then makes the necessary changes to the rest of the file system. After all transactions are completed successfully, the entries are deleted from magazine . This provides best preservation system integrity and reduces the likelihood of data loss. It should be noted that Linux supports access to Windows -sections.

File system Linux has only one root directory, which is indicated by a slash ( / ). In the file structure Linux no disks A, B, C, D ...., but there are only catalogs. IN Linux There is a difference between upper and lower case letters in commands, file names and directory names. IN Windows Each file has only one name, in Linux there can be many of them. This - " hard » links that point directly to a file inode. A hard link is one of the principles of file system organization. Linux .

OS directory structure Linux presented in table. 1. There are also some useful abbreviations for directory names:

  • Single point ( . ) denotes the current working directory.
  • Two dots ( .. ) indicate the parent directory of the current worker.
  • Tilda ( ~ ) indicates the user's home directory (usually the directory that is the current working directory when Bash is started).

Table 1

/ Root directory
/bin Contains executable files of the most necessary programs for the system. Catalog /bin does not contain subdirectories.
/boot Here is the system kernel itself (file vmlinuz-...) and the files necessary to download it.
/dev Catalog /dev contains device files (drivers).
/etc This is a directory of configuration files, i.e. files containing information about system settings (for example, program settings).
/home Contains the home directories of system users.
/lib This is where libraries (functions needed by many programs) are located.
/media Contains subdirectories that are used as mount points for removable devices (CD-ROMs, floppy disks, etc.)
/mnt This directory (or its subdirectories) can serve as a mount point for temporarily mounted file systems.
/proc Contains files with information about processes running on the system.
/root This is the system administrator's home directory.
/sbin Contains executable programs, like a directory /bin. However, only the system administrator can use programs located in this directory ( root).
/tmp A directory for temporary files that store intermediate data necessary for the operation of certain programs and are deleted after the program is completed.
/usr Directory for most programs that are not important for system boot. The structure of this directory actually duplicates the structure of the root directory.
/var Contains data that was obtained during the operation of some programs and must be transferred to others, and log files with information about the operation of the system.

LABORATORY WORKS

There are two types of interface: graphical user interface and command line interface.

Graphical User Interface (English: Graphical user interface, GUI).- control programs using graphic buttons, pop-up menus, windows and other elements. Many actions can be performed using the mouse.

Advantages: visual display of programs and their contents; program capabilities can be studied without reading documentation.

Command Line Interface (English: Command Line Interface, CLI).- program management using commands. Commands consist of letters, numbers, symbols, are typed line by line, and are executed after pressing the Enter key. The main instrument here is the keyboard.
This interface is built into the system core and will be available even if the graphical interface does not start.

Advantages: low resource consumption, flexibility when compiling a list of actions from commands, the ability automatic execution commands, ability to copy and paste commands.

If we compare the interfaces in different systems, then you can see that the basic commands are the same in all distributions of the Linux family, but the graphical programs in each system can vary greatly.

There are two ways to get to the command line: through the console or terminal.

Console

When Ubuntu boots, seven full-screen consoles are launched, each with its own independent session, the first through the sixth with a command line interface, the seventh starts in graphical mode. The user sees only the graphic mode during loading.
You can switch to one of the virtual consoles by pressing the key combination:
Ctrl+Alt+F1 - first virtual console;
Ctrl+Alt+F2 - second virtual console;
Ctrl+Alt+F3 - third virtual console;
Ctrl+Alt+F4 - fourth virtual console;
Ctrl+Alt+F5 - fifth virtual console;
Ctrl+Alt+F6 - sixth virtual console;
Ctrl+Alt+F7 - seventh virtual console, return to graphical mode.

Terminal

Terminal- a graphical program that emulates a console.
Such programs allow you, without leaving graphics mode execute commands.
The terminal has additional functionality compared to the console (mouse control, context menu, scroll bar, tabs, launching multiple windows, main menu, graphic settings).

You can start the terminal as follows:

In Unity:
Main menu → Dial to search bar word Terminal
or press the key combination: Ctrl + Alt + T

In Gnome Fallback
Applications → Accessories → Terminal

In Xfce (Xubuntu):

In KDE (Kubuntu):
Main menu → Applications → System → Terminal

In LXDE (Lubuntu):
Main menu → System → LXTerminal

After launching the terminal, we see a line prompting us to enter commands, for example:
vladimir@Zotac-Zbox-Nano:~$

vladimir - user account name
@ - separator between account and computer name
Zotac-Zbox-Nano - computer name
: - delimiter
~ - in which folder the command is executed, ~ is the user’s home folder, if you run the ls command you will get a list of files from this folder
$ - an invitation to execute a command with ordinary user rights (# will mean an invitation to execute commands with administrator rights)

Hotkeys

Copying commands

Often you will have to follow some instructions that require you to copy commands into the terminal. You might be surprised to find that the text you copied from a web page using the Ctrl + C key combination is not pasted into the terminal when you press Ctrl + V. So, do you really have to retype all these commands and file names manually? No, relax! There are three ways to paste text into the terminal: Ctrl + Shift + V, by clicking the middle mouse button or right mouse button and selecting the “Paste” line.

Set savings

or Ctrl + Pscroll up recently used commands
↓ or Ctrl + Nscroll down recently used commands
Enterexecute the selected command
TabAn extremely convenient feature is auto-substitution of commands and file names. If only one command begins with the selected characters, it will be substituted, and if there are several of them, then double-clicking tab will display a list of all possible options.
Ctrl+Rsearch for commands that you have entered before. If you need to re-execute a very long and complex command, you can enter only part of it, and this key combination will help you find the entire command.
History Team history displays a list of all the commands you have entered. Each team will be assigned a number. To run command number x, simply enter "!x". If your story is too long, you can try "history I have less", this will make the list scrollable.

Changing text

The mouse doesn't work here. Use the left/right arrows to move around the line.

Keyboard input will add characters. Existing text will not be deleted.

Software shell

The console and terminal process commands using a shell program.
The shell is a command interpreter; it recognizes commands entered on the command line and launches programs to execute the command.
Ubuntu uses the bash shell by default and recognizes commands in the bash language.
Bash can be replaced with another shell, there are several of them. Each shell has its own set of settings and capabilities.
(auto-execute commands when entering the shell, internal teams shells, history keeping, you can assign shortened commands - aliases).

Teams

Commands are a predefined set of letters, numbers, and symbols that can be entered in the command line and executed by pressing enter.

Teams are divided into two types:

    Commands built into the shell (for example history)

    Commands that control programs installed on the system

Commands for managing programs are built according to the following scheme:

Program_name - key value

Program name- this is the name of the executable file from the directories written in the $PATH variable (/bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin, etc.) or the full path to executable file (/opt/deadbeef/bin/deadbeef)
Key- written after the program name, for example -h, each program has its own set of switches, they are listed in the program help, the keys are used to indicate which settings to use or what action to perform
Meaning- address, numbers, text, special characters (*, ~, \, &, " ", _), variables ($HOME, $USER, $PATH)

You can run the commands as follows:

    Type the command in the command line and press Enter

    Copy the command from the instructions and paste it into the command line, then press Enter

    Create a script and execute it by double-clicking the mouse (create a text file, write #!/bin/bash in the first line, write the commands in the column below, save, allow execution in the file properties, double-click on the file to execute all the listed commands)

Remember that the terminal is case sensitive! The words User, user and USER are different in Linux!

Command Cheat Sheet

File commands

cd ../.. go to the directory two levels higher
CD go to home directory
cd ~user go to user's home directory
cd- go to the directory you were in before moving to the current directory
pwd show current directory
mkdir dir create directory dir
mkdir dir1 create a directory named "dir1"
mkdir dir1 dir2 create two directories at the same time
mkdir -p /tmp/dir1/dir2 create a directory tree
rm file delete file
rm -r dir delete directory dir
rm -f file force delete file
rm -rf dir force delete directory dir
rm -f file1 delete file named "file1"
rmdir dir1 delete directory named "dir1"
rm -rf dir1 delete the directory named "dir1" and recursively all its contents
rm -rf dir1 dir2 delete two directories and their contents recursively
cp file1 file2 copy file1 to file2
cp -r dir1 dir2 copy dir1 to dir2; will create directory dir2 if it does not exist
cp dir/ copy all files in directory dir to current directory
cp -a /tmp/dir1 copy directory dir1 with all contents to the current directory
cp -a dir1 dir2 copy directory dir1 to directory dir2
mv dir1 new_dir rename or move a file or directory
mv file1 file2 rename or move file1 to file2. if file2 is an existing directory - move file1 to file2 directory
ln -s file1 lnk1 create a symbolic link to a file or directory
ln file1 lnk1 create a “hard” (physical) link to a file or directory
touch file create file
touch -t 0712250000 fileditest modify the date and time of file creation; if it is missing, create a file with the specified date and time (YYMMDDhhmm)
cat > file direct standard input to file
more file print the contents of file
head file print first 10 lines of file
tail file print last 10 lines of file
tail -f file print the contents of the file as it grows, starting from the last 10 lines

Archiving

tar cf file.tar files create a tar archive named file.tar containing files
tar xf file.tar unpack file.tar
tar czf file.tar.gz files create a tar archive with Gzip compression
tar xzf file.tar.gz unpack tar with Gzip
tar cjf file.tar.bz2 create a tar archive with Bzip2 compression
tar xjf file.tar.bz2 unpack tar with Bzip2
gzip file compress the file and rename it to file.gz
gzip -d file.gz decompress file.gz to file
bunzip2 file1.bz2 decompresses the file "file1.gz"
gzip -9 file1 compress file file1 with maximum compression
rar a file1.rar test_file create a rar archive "file1.rar" and include the file test_file in it
rar a file1.rar file1 file2 dir1 create a rar archive "file1.rar" and include file1, file2 and dir1 in it
rar x file1.rar unpack rar archive
tar -cvf archive.tar file1 create a tar archive archive.tar containing file file1
tar -cvf archive.tar file1 file2 dir1 create a tar archive archive.tar containing file1, file2 and dir1
tar -tf archive.tar show archive contents
tar -xvf archive.tar unpack the archive
tar -xvf archive.tar -C /tmp unpack the archive to /tmp
tar -cvfj archive.tar.bz2 dir1 create an archive and compress it using bzip2 (Translator's note: the -j switch does not work on all *nix systems)
tar -xvfj archive.tar.bz2 decompress the archive and unpack it (Translator's note: the -j switch does not work on all *nix systems)
tar -cvfz archive.tar.gz dir1 create an archive and compress it using gzip
tar -xvfz archive.tar.gz decompress the archive and unpack it
zip file1.zip file1 create a compressed zip archive
zip -r file1.zip file1 file2 dir1 create a compressed zip archive including several files and/or directories
unzip file1.zip decompress and unpack the zip archive

Working with local deb packages (dpkg)

deb - file name extension for “binary” packages for distribution and installation software in the OS of the Debian project, and others using the dpkg package management system. Deb is part of the word Debian, in turn derived from the words Debra - the name of the girlfriend (later wife, now former) of Debian founder Ian Murdoch and Ian from his own name.

dpkg -i package.deb install/update package
dpkg -r package_name remove a package from the system
dpkg -l show all packages installed on the system
dpkg -l | grep httpd Among all the packages installed on the system, find a package containing “httpd” in its name
dpkg -s package_name display information about a specific package
dpkg -L package_name display a list of files included in the package installed on the system
dpkg –contents package.deb display a list of files included in a package that is not yet installed on the system
dpkg -S /bin/ping find the package that contains the specified file

Using the Apt package manager

apt (advanced packaging tool) - program for installing, updating and uninstalling software packages on Debian and Debian-based operating systems (Ubuntu, Linux Mint, etc.), sometimes also used in Mandrake-based distributions such as Mandriva, ALTLinux and PCLinuxOS. Capable of automatically installing and configuring programs for UNIX-like operating systems, both from pre-compiled packages and from source code.

apt-get install package_name install/update package
apt-cdrom install package_name install/update the package from cdrom
apt-get update get updated package lists
apt-get upgrade update packages installed on the system
apt-get remove package_name remove a package installed on the system while saving the configuration files
apt-get purge package_name remove a package installed on the system by deleting configuration files
apt-get check check dependency integrity
apt-get clean delete downloaded archive files packages
apt-get autoclean remove old downloaded package archive files

Viewing file contents

cat file1 print the contents of file1 to standard output
tac file1 print the contents of file1 to the standard output device in reverse order ( last line become the first, etc.)
more file1 paging the contents of file1 to standard output
less file1 page-by-page output of the contents of file1 to the standard output device, but with the ability to scroll in both directions (up and down), search by content, etc.
head -2 file1 Print the first two lines of file1 to standard output. Ten lines are output by default
tail -2 file1 Print the last two lines of file1 to standard output. Ten lines are output by default
tail -f /var/log/messages print the contents of the file /var/log/messages to standard output as text appears in it

Text manipulation

cat file_original | > result.txt general syntax for performing actions to process the contents of a file and output the result to a new one
cat file_original | » result.txt general syntax for performing actions to process the contents of a file and output the result to existing file. If the file does not exist, it will be created
grep Aug /var/log/messages from file "/var/log/messages" select and print to standard output lines containing "Aug"
grep ^Aug /var/log/messages from file "/var/log/messages" select and print to standard output lines starting with "Aug"
grep /var/log/messages from file "/var/log/messages" select and print to standard output strings containing numbers
grep Aug -R /var/log/* select and print to standard output lines containing "Aug" in all files located in the /var/log directory and below
sed "s/stringa1/stringa2/g" example.txt in the example.txt file replace “string1” with “string2”, output the result to the standard output device
sed "/^$/d" example.txt remove empty lines from example.txt file
sed "/*#/d; /^$/d" example.txt remove empty lines and comments from example.txt file
echo "esempio" | tr "[:lower:]" "[:upper:]" convert characters from lowercase to uppercase
sed -e "1d" result.txt remove first line from example.txt file
sed -n "/string1/p" display only strings containing "string1"
sed -e "s/ *$ " example.txt |remove blank characters at the end of each line | | sed -e "s/string1 g" example.txt remove the string “string1” from the text without changing anything else
sed -n "1.8p;5q" example.txt take the first to eighth lines from the file and print the first five from them
sed -n "5p;5q" example.txt print the fifth line
sed -e "s/0*/0/g" example.txt replace a sequence of any number of zeros with a single zero
cat -n file1 number the lines when outputting the file contents
cat example.txt | awk "NR%2==1" When outputting the contents of a file, do not output even lines of the file
echo a b c | awk "(print $1)" display the first column. Separate, by default, by space/spaces or character/tab characters
echo a b c | awk "(print $1,$3)" display the first and third columns. Separate, by default, by space/spaces or character/tab characters
paste file1 file2 combine the contents of file1 and file2 as a table: line 1 of file1 = line 1 column 1-n, line 1 of file2 = line 1 column n+1-m
paste -d "+" file1 file2 combine the contents of file1 and file2 as a table with a “+” delimiter
sort file1 file2 sort the contents of two files
sort file1 file2 | uniq sort the contents of two files without showing duplicates
sort file1 file2 | uniq -u sort the contents of two files, displaying only unique lines (lines that appear in both files are not printed to standard output)
sort file1 file2 | uniq -d sort the contents of two files, showing only duplicate lines
comm -1 file1 file2 compare the contents of two files without displaying lines belonging to file "file1"
comm -2 file1 file2 compare the contents of two files without displaying lines belonging to file "file2"
comm -3 file1 file2 compare the contents of two files, removing lines found in both files

Converting character sets and file formats

File system analysis

Mounting file systems

Mounting a file system is the process that prepares a disk partition for use. operating system.

The mounting operation consists of several stages:

    Determining the type of system to be mounted

    Checking the integrity of the mounted system

    Reading system data structures and initializing the corresponding module file manager(file system drivers)

    Setting a flag indicating the end of the mount. When correctly unmounted, this flag is reset. If during boot the system determines that the flag is not reset, then the work was completed incorrectly, and perhaps the FS needs to be repaired

    Incorporating a new file system into a shared namespace

mount /dev/hda2 /mnt/hda2 mounts the "hda2" partition to the "/mnt/hda2" mount point. Make sure there is a mount point directory "/mnt/hda2"
umount /dev/hda2 will unmount the "hda2" partition. Before executing, leave "/mnt/hda2"
fuser -km /mnt/hda2 forcefully unmount the partition. Applies when the partition is occupied by some user
umount -n /mnt/hda2 perform unmounting without entering information into /etc/mtab. Useful when the file has read-only attributes or there is not enough disk space
mount /dev/fd0 /mnt/floppy mount floppy disk
mount /dev/cdrom /mnt/cdrom mount CD or DVD
mount /dev/hdc /mnt/cdrecorder mount CD-R/CD-RW or DVD-R/DVD-RW(+-)
mount -o loop file.iso /mnt/cdrom mount ISO image
mount -t vfat /dev/hda5 /mnt/hda5 mount Windows FAT32 file system

Formatting file systems

Formatting - software process marking the data storage area of ​​electronic media located on the magnetic surface ( hard disks, floppy disks), optical media (CD/DVD/Blu-ray discs), solid state drives(flash memory - flash module, SSD), etc. There are different ways this process.

Formatting itself consists of creating (forming) data access structures, for example, file system structures. In this case, the possibility of direct access to the information located (which was located before formatting) on ​​the storage medium is lost, part of it is irretrievably destroyed. Some software utilities make it possible to recover some (usually a large part) of information from formatted media. The formatting process can also check and correct the integrity of the media.

Creating backups

Backup is the process of creating a copy of data on a medium (hard drive, floppy disk, etc.) designed to restore data to its original or new location in the event of damage or destruction.

dump -0aj -f /tmp/home0.bak /home create a complete backup copy/home directory to file /tmp/home0.bak
dump -1aj -f /tmp/home0.bak /home create an incremental backup of the /home directory to the file /tmp/home0.bak
restore -if /tmp/home0.bak restore from backup /tmp/home0.bak
rsync -rogpav –delete /home /tmp sync /tmp with /home
rsync -rogpav -e ssh –delete /home ip_address:/tmp synchronize via SSH tunnel
rsync -az -e ssh –delete ip_addr:/home/public /home/local synchronize a local directory with a remote directory via a compressed ssh tunnel
rsync -az -e ssh –delete /home/local ip_addr:/home/public synchronize a remote directory with a local directory via a compressed ssh tunnel
dd bs=1M if=/dev/hda | gzip | ssh user@ip_addr "dd of=hda.gz" make a "cast" local disk to a file on a remote computer via an ssh tunnel
tar -Puf backup.tar /home/user create an incremental backup of the "/home/user" directory to the backup.tar file while preserving the permissions
(cd /tmp/local/ && tar c .) | ssh -C user@ip_addr "cd /home/share/ && tar x -p" copying the contents of /tmp/local to a remote computer via an ssh tunnel to /home/share/
(tar c /home) | ssh -C user@ip_addr "cd /home/backup-home && tar x -p" copying the contents of /home to a remote computer via an ssh tunnel to /home/backup-home
tar cf - . | (cd /tmp/backup ; tar xf -) copying one directory to another while maintaining powers and links
find /home/user1 -name "*.txt" | xargs cp -av –target-directory=/home/backup/ –parents search /home/user1 for all files whose names end in ".txt" and copy them to another directory
find /var/log -name "*.log" | tar cv –files-from=- | bzip2 > log.tar.bz2 search /var/log for all files whose names end in ".log" and create a bzip archive from them
dd if=/dev/hda of=/dev/fd0 bs=512 count=1 create a copy of the MBR (Master Boot Record) from /dev/hda to a floppy disk
dd if=/dev/fd0 of=/dev/hda bs=512 count=1 recover MBR from floppy disk to /dev/hda

Disk space

df -h displays information about mounted partitions, showing total, available and used space (Translator's note: the -h switch does not work on all *nix systems)
ls -lSr |more displays a list of files and directories recursively sorted by ascending size and allows page-by-page browsing
du -sh dir1 calculates and displays the size occupied by the directory "dir1" (Translator's note: the -h switch does not work on all *nix systems)
du -sk * | sort -rn displays the size and names of files and directories, sorted by size
rpm -q -a –qf "%10(SIZE)t%(NAME)n" | sort -k1,1n shows the amount of used disk space occupied by rpm package files, sorted by size (fedora, redhat, etc.)
dpkg-query -W -f="$(Installed-Size;10)t$(Package)n" | sort -k1,1n shows the amount of used disk space occupied by deb package files, sorted by size (ubuntu, debian, etc.)

CDROM

mkisofs /dev/cdrom > cd.iso create iso image disk
mkisofs /dev/cdrom | gzip > cd_iso.gz create a compressed iso disk image
mkisofs -J -allow-leading-dots -R -V “Label CD” -iso-level 4 -o ./cd.iso data_cd create an iso image of the folder
cdrecord -v dev=/dev/cdrom cd.iso burn iso image
gzip -dc cd_iso.gz | cdrecord dev=/dev/cdrom burn compressed iso image
mount -o loop cd.iso /mnt/iso mount iso image
cd-paranoia -B read audio tracks from disk into wav files
cd-paranoia – “-3” count the first three audio tracks from the disk into wav files
cdrecord –scanbus identify scsi channel

Users and groups

groupadd group_name create new group with the name group_name
groupdel group_name delete group group_name
groupmod -n new_group_name old_group_name rename group old_group_name to new_group_name
useradd -c "Nome Cognome" -g admin -d /home/user1 -s /bin/bash user1 create user user1, assign him /home/user1 as his home directory, /bin/bash as shell, include him in the admin group and add the Nome Cognome comment
useradd user1 create user user1
userdel -r user1 delete user1 and his home directory
usermod -c "User FTP" -g system -d /ftp/user1 -s /bin/nologin user1 change user attributes
passwd Change password
passwd user1 change user1 password (root only)
chage -E 2005-12-31 user1 set the expiration date for the user account user1
pwck check for correctness system files accounts. The files /etc/passwd and /etc/shadow are checked
grpck checks the correctness of system account files. The file /etc/group is checked
newgrp [-] group_name changes the current user's primary group. If you specify "-", the situation will be identical to that in which the user logged out and logged in again. If you do not specify a group, the primary group will be assigned from /etc/passwd

Setting/changing file permissions

chmod (from the English change mode) is a program for changing access rights to files and directories. The name comes from the Unix OS program chmod, which, in fact, changes access rights to files, directories and symbolic links.

ls -lh viewing permissions for files and directories in the current directory
ls /tmp | pr -T5 -W$COLUMNS print the contents of the /tmp directory and split the output into five columns
chmod ugo+rwx directory1 add permissions to directory1 ugo(User Group Other)+rwx(Read Write eXecute) - full rights for everyone. A similar thing can be done this way chmod 777 directory1
chmod go-rwx directory1 take away all permissions for the directory1 from the group and everyone else
chown user1 file1 assign file1 owner to user1
chown -R user1 directory1 recursively assign the owner of directory1 to user1
chgrp group1 file1 change the owner group of file file1 to group1
chown user1:group1 file1 change the owner and group of the owner of file file1
find / -perm -u+s find, starting from the root, all files with the SUID set

Popular meanings

400 (-r--–) The owner has the right to read; no one else has the right to perform any actions
644 (-rw-r–r–) All users have read permission; owner can edit
660 (-rw-rw--) Owner and group can read and edit; the rest have no right to perform any actions
664 (-rw-rw-r–) All users have read permission; owner and group can edit
666 (-rw-rw-rw-) All users can read and edit
700 (-rwx--) The owner can read, write and execute; no one else has the right to perform any actions
744 (-rwxr–r–) Each user can read, the owner has the right to edit and execute
755 (-rwxr-xr-x) Each user has the right to read and execute; owner can edit
777 (-rwxrwxrwx) Each user can read, edit and execute
1555 (-r-xr-xr-t) Each user has the right to read and execute; Only the owner of the file can delete a file
2555 (-r-xr-sr-x) Each user has the right to read and execute with the rights of the user group of the file owner
4555 (-r-sr-xr-x) Each user has the right to read and execute with the rights of the file owner

Secure Shell (ssh) Commands

SSH (Secure Shell) is an application-level network protocol that allows remote control of the operating system and tunneling of TCP connections (for example, for file transfer). Similar in functionality to the Telnet and rlogin protocols, but, unlike them, it encrypts all traffic, including transmitted passwords. SSH allows a choice of different encryption algorithms. SSH clients and SSH servers are available for most network operating systems.

SSH allows you to securely transfer almost any other network protocol in an unsecured environment. Thus, you can not only work remotely on your computer via command shell, but also transmit an audio stream or video (for example, from a webcam) over an encrypted channel. SSH can also use compression of transmitted data for subsequent encryption, which is convenient, for example, for remotely launching X Window System clients.

Most hosting providers provide clients with SSH access to their home directory for a fee. This can be convenient both for working on the command line and for remotely launching programs (including graphical applications).

Process management

A process is a program that is currently running. The ISO 9000:2000 standard defines a process as a set of interrelated and interacting activities that transform incoming data into outgoing data. A computer program itself is only a passive collection of instructions, while a process is the actual execution of those instructions. Also, a process is a running program and all its elements: address space, global variables, registers, stack, open files, etc.

top show all running processes
ps list your currently active processes
ps-eafw display running processes, the resources they use, and other useful information(one time)
ps -e -o pid,args –forest display PIDs and processes in the form of a tree
pstree display process tree
kill -9 98989 “kill” the process with PID 98989 “to death” (without respecting data integrity)
kill -TERM 98989 Correctly terminate the process with PID 98989
kill -1 98989 force the process with PID 98989 to reread the configuration file
lsof -p 98989 display a list of files opened by the process with PID 98989
lsof /home/user1 display a list of open files from the /home/user1 directory
strace -c ls >/dev/null list system calls, created and received by the ls process
strace -f -e open ls >/dev/null display library calls
watch -n1 "cat /proc/interrupts" display interrupts in real time
last reboot display system reboot history
last user1 display the registration history of user1 in the system and the time he spent in it
lsmod display loaded kernel modules
free -m show status random access memory in megabytes
smartctl -A /dev/hda condition monitoring hard drive/dev/hda via SMART
smartctl -i /dev/hda check SMART availability on hard drive /dev/hda
tail /var/log/dmesg withdraw ten latest entries from the kernel boot log
tail /var/log/messages display the last ten entries from the system log

Network (LAN and WiFi)

ifconfig eth0 show configuration of network interface eth0
ifup eth0 activate (raise) interface eth0
ifdown eth0 deactivate (lower) interface eth0
ifconfig eth0 192.168.1.1 netmask 255.255.255.0 set the eth0 interface to an IP address and subnet mask
ifconfig eth0 promisc switch the eth0 interface to promiscuous mode to “catch” packets (sniffing)
ifconfig eth0 -promisc disable promiscuous mode on interface eth0
dhclient eth0 activate interface eth0 in dhcp mode
route -n display local routing table
route add -net 0/0 gw IP_Gateway set the default gateway IP address
route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.1.1 add a static route to the network 192.168.0.0/16 via a gateway with IP address 192.168.1.1
route del 0/0 gw IP_gateway remove the default gateway IP address
echo "1" > /proc/sys/net/ipv4/ip_forward allow packet forwarding
hostname display computer name
host www.linuxguide.it resolve host name www.linuxguide.it to ip address and vice versa *host 62.149.140.85*
ip link show* display the status of all interfaces
mii-tool eth0 display status and connection type for interface eth0
ethtool eth0 displays interface statistics for eth0, showing information such as supported and current connection modes
netstat -tupn displays all established network connections via TCP and UDP protocols without resolving names to IP addresses and PIDs and the names of the processes providing these connections
netstat -tupln displays all network connections via TCP and UDP protocols without name resolution to IP addresses and PIDs and names of processes listening on ports
tcpdump tcp port 80 display all traffic on TCP port 80 (usually HTTP)
iwlist scan scan the airwaves for the availability of wireless access points
iwconfig eth1 show configuration of wireless network interface eth1

Microsoft Windows networks(SAMBA)

IPTABLES (firewall)

iptables is a command line utility standard interface control the operation of the firewall (firewall) netfilter for kernels Linux versions 2.4, 2.6, 3.x, 4.x. Superuser (root) privileges are required to use the iptables utility.

iptables -t filter -nL show all rule chains
iptables -t nat -L display all rule chains in the NAT table
iptables -t filter -F clear all rule chains in the filter table
iptables -t nat -F clear all rule chains in the NAT table
iptables -t filter -X delete all custom rule chains in the filter table
iptables -t filter -A INPUT -p tcp –dport telnet -j ACCEPT allow incoming telnet connection
iptables -t filter -A OUTPUT -p tcp –dport http -j DROP block outgoing HTTP connections
iptables -t filter -A FORWARD -p tcp –dport pop3 -j ACCEPT Allow POP3 connections to be forwarded
iptables -t filter -A INPUT -j LOG –log-prefix “DROP INPUT” enable kernel logging of packets passing through the INPUT chain and adding the prefix “DROP INPUT” to the message
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE enable NAT (Network Address Translate) of outgoing packets on the eth0 interface. Acceptable when used with dynamically allocated IP addresses
iptables -t nat -A PREROUTING -d 192.168.0.1 -p tcp -m tcp –dport 22 -j DNAT –to-destination 10.0.0.2:22 redirecting packets addressed to one host to another host

System information

arch display computer architecture
uname -r display the kernel version used
dmidecode -q show hardware system components - (SMBIOS/DMI)
hdparm -i /dev/hda display hard drive characteristics
hdparm -tT /dev/sda test the performance of reading data from the hard drive
cat /proc/cpuinfo display processor information
cat /proc/interrupts show interrupts
cat /proc/meminfo check memory usage
cat /proc/swaps show swap file(s)
cat /proc/version display kernel version
cat /proc/net/dev show network interfaces and statistics on them
cat /proc/mounts display mounted file systems
lspci-tv show as a tree of PCI devices
lsusb -tv show as USB device tree
date display system date
Cal 2007 display a calendar table for the year 2007
date 041217002007.00 set the system date and time MMDDDHHmmYYYY.SS (MonthDayHourMinutesYear.Seconds)
clock -w save system time in BIOS
uptime show current uptime
w show online users
whoami the name you are logged in under
finger user show information about user
uname -a show kernel information
cat /proc/cpuinfo CPU information
cat /proc/meminfo memory information
man command show manual for command
df show info about using disks
du display the “weight” of the current directory
free memory and swap usage
whereis app possible location of the app program
which app which app will be launched by default

Stopping the system

Other Useful Commands

apropos ...keyword displays a list of commands that in one way or another relate to keywords. Useful when you know what the program does, but don't remember the command
man ping calling the program manual, in this case, ping
whatis...keyword displays a description of the actions of the specified program
ldd /usr/bin/ssh display a list of libraries required for ssh to work
alias hh="history" assign an alias hh to the history command
find . -maxdepth 1 -name *.jpg -print -exec convert Resizing all images in a folder, passing ImageMagick's "convert" utility to create smaller copies of the images (preview)
swapon /dev/hda3 activate the swap space located on the hda3 partition
swapon /dev/hda2 /dev/hdb3 activate swap spaces located on hda2 and hdb3 partitions

View program help and manuals

The names of programs used in commands that may be useful need to be learned or printed, and how to use them can be found out at any time by calling up the help or manual for the program.

For getting quick guide According to the program, you need to do:

man program

You can move around using the arrow keys, and exit it by pressing the Q key. For more details, see man man

To get help indicating the keys, you need to run:

Program -h program --help

Both options should work the same, but some program authors leave one of these keys, so try both if necessary.

Search by man

If you are not sure which command you need, try searching through the manual texts.

    Man-k something-you-need

    will look for what you need in all manuals. Try:

    Man-k nautilus

    to see how it works. By the way, this is the same as running the apropos command.

    Man -f something-you-need

    will search only by the names of system manuals. Try:

    Man -f gnome

    For example, running the whatis command will produce the same result.

More attractive men

Gnome/Unity desktop users can take advantage of the yelp utility, which provides a simple GUI, by running the command in the console

Yelp man:<команда>

Users with Konqueror installed can read manual pages and search them in a web browser context, decorated with selected wallpapers. To do this, type Konqueror in the address bar and use the command:

Man:/<команда>

Execute commands with unlimited privileges

Most of the commands listed below must be preceded by the command:

This temporarily gives you superuser rights, which are necessary to work with files and directories that do not belong to your account. Using sudo requires a password. Only users with such administrative privileges can use this command.

Commands for working with files and folders

    The tilde character (~) represents your home folder. If you user, then the tilde (~) is /home /user.

    The pwd (“print working directory”) command allows you to find out which directory you are currently in. Remember, however, that Gnome Terminal always displays this same information in the window title.

    Ls will show you all the files in the current directory. If you use this command with certain options, you can also enable display of file sizes, time last change and rights to files. For example: ls ~

    will show everything you have in your home folder.

    The cd command changes the working directory. When you first launch the terminal, you will be in your home folder. To navigate the file system you need to use cd . Examples:

    1. To get to the root directory, run: cd /

      To get to your home folder, run: cd ~

      To move up one directory use: cd ..

      To return to the previously visited directory, use: cd -

      To move through several directories at a time, you need to write the full path of the folder you want to move to. For example, command: cd /var/www

      will move you to the /www subdirectory of the /var/ directory. And the command:

      Cd ~/Desktop\

      will take you to your desktop. In this case, "\" means escaping a space.

    The cp command copies a file. For example, the command: cp text new

    will create an exact copy of the “text” file and name it “new”, while the “file” will not disappear anywhere. To copy a directory you need to use the command:

    Cp -r directory new

    where the -r option denotes recursive copying.

    The mv command moves a file to a different location or simply renames the file. For example, the command: mv file text

    will rename "file" to "text".

    Mv text ~/Desktop\desk

    will move "text" to your desktop, but will not rename it. To still rename a file, you need to specifically specify a new name for it. You can replace the path to your home folder with "~" to speed things up. Remember that when using mv with sudo, the terminal also binds "~" to your home folder. However, if you enable a root session in the console using sudo -i or sudo -s , then "~" will refer to the root of the drive, not your home directory.

    The rm command deletes a file.

    The rmdir command deletes an empty folder. To delete a folder along with all its attachments, use rm -r instead.

    Mkdir This command creates a directory. The mkdir music command will create a folder for you called “music”.

    Man try this command when you want to read the inline description of another command. For example: man man

    will show you a description of this command itself.

System Information Commands

    Team df shows the amount of occupied disk space on all mounted partitions. Most useful: df -h

    Because it uses Megabytes (M) and Gigabytes (G) for display, not blocks. -h means "human readable".

    du displays the amount of disk space occupied by a specific folder. It can show information for all subdirectories separately or for the folder as a whole. .. user@users-desktop:~$ du /media/floppy 1032 /media/floppy/files 1036 /media/floppy/ user@users-desktop:~$ du -sh /media/floppy 1.1M /media/floppy/

    S stands for "summary" and -h stands for "human readable".

    free displays the amount of free and used RAM. Command: free -m

    shows information in Megabytes.

    top Displays information about your system, running processes and system resources, including CPU load, RAM and swap usage, and number of running processes. To stop top, press Q.

There are also several other wonderful and very necessary utilities, designed in the top style:

    htop analogue of top, much superior in capabilities

    iftop information about active network connections, network download/upload speed

    iotop information about processes performing active disk operations

    uname with the -a option, displays all system information, including machine name, kernel version and other details. The most useful of this is checking the kernel version.

    Passwd newuser

Building a directory tree

The utility displays the directory tree in a beautifully formatted form. The tree package is in Ubuntu repositories, so the installation is done in one line:

sudo apt-get install tree

To display a directory tree, the command should look like this:

tree -dA test