Command line. Basic Linux and Unix console commands Basic ubuntu commands
There are two kinds of interface: graphical user interface and command line interface.
Graphical user interface (Eng. Graphical user interface, GUI).- control programs using graphic buttons, pop-up menus, windows and other elements. Many actions can be performed with the mouse.
Advantages: visual display of programs and their contents, program features can be studied without reading the documentation.
Command line interface (English Command Line Interface, CLI).- program management using commands. Commands consist of letters, numbers, symbols, are typed line by line, are executed after pressing the Enter key. The main instrument here is the keyboard.
This interface is built into the system kernel, it will be available even if the graphical interface does not start.
Advantages: low resource consumption, flexibility in compiling a list of actions from commands, the ability to automatic execution commands, the ability to copy and paste commands.
If you compare the interfaces in different systems, you can see that the basic commands are the same in all distributions Linux families, but the graphics programs on each system can vary greatly.
There are two ways to get to the command line: through the console or the terminal.
Console
During Ubuntu boot, 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 the graphical mode. The user sees only the graphical mode during the boot.
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 - the sixth virtual console;
Ctrl+Alt+F7 - the seventh virtual console, return to graphics mode.
Terminal
Terminal - graphics program emulation console.
Such programs allow you to execute commands without leaving the graphical mode.
The terminal, compared to the console, has additional functionality (mouse control, context menu, scrollbar, tabs, launch multiple windows, main menu, graphic settings).
You can start the terminal like this:
In Unity:
Main menu → Type the word Terminal in the search bar
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 starting the terminal, we see a line with an invitation to enter commands, for example:
[email protected]:~$
vladimir - user account name
@ - separator between account and computer name
Zotac-Zbox-Nano - computer name
: - separator
~ - 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 the rights of a simple user (# will mean an invitation to execute commands with administrator rights)
Hotkeys
Copy commands
Often you will have to follow some instructions that require you to copy commands to the terminal. You will probably be surprised when you find that the text you copied from a web page using the combination Ctrl keys+ C, is not pasted into the terminal when pressing Ctrl + V . And what, 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 , pressing the middle mouse button or right mouse button and selecting the Paste line.
Set savings
or ctrl+p | scroll up recently used commands |
↓ or Ctrl + N | scroll down recently used commands |
Enter | execute the selected command |
Tab | an extremely convenient feature - auto-completion of commands and file names. If only one command starts with the selected characters, it will be substituted, and if there are several, then double-clicking tab will display a list of all possible options. |
ctrl+r | search for commands 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 keyboard shortcut will help you find the entire command. |
History | Team history prints out a list of all the commands you entered. Each team will be assigned a number. To run command number x, just type "!x". If your story is too long, you can try "history I'm less", this will make the list scrollable. |
Text change
The mouse doesn't work here. Use the left/right arrows to move through the line.
Keyboard input will add characters. Existing text will not be deleted.
Shell
The console and terminal process commands using a shell program.
A shell program 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 it recognizes commands in the bash language.
Bash can be replaced by another shell, there are several. Each shell has its own set of settings and features.
(auto-execution of commands when entering the shell, internal shell commands, history keeping, you can assign abbreviated commands - aliases).
Teams
Commands are a predefined set of letters, numbers, symbols that can be entered on the command line and executed by pressing enter.
Commands are divided into two types:
Commands built into the shell (eg 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 recorded in the $PATH variable (/bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin, etc.) or the full path to executable (/opt/deadbeef/bin/deadbeef)
Key- is written after the name of the program, for example -h, each program has its own set of switches, they are listed in the help for the program, the switches 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 commands like this:
Type the command on the command line and press Enter
Copy the command from the instruction and paste it into the command line, then press Enter
Create a script and double-click (create a text file, write #!/bin/bash in the first line, write commands in a column below, save, enable 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 above |
cd | go to home directory |
cd ~user | go to user's home directory |
cd- | change to the directory where you were before changing 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 directory tree |
rm file | delete file |
rm -r dir | remove directory dir |
rm -f file | force delete file |
rm -rf dir | force delete directory dir |
rm -f file1 | delete file named "file1" |
rmdir dir1 | remove directory named "dir1" |
rm -rf dir1 | delete directory named "dir1" and recursively all its contents |
rm -rf dir1 dir2 | remove two directories and recursively their contents |
cp file1 file2 | copy file1 to file2 |
cp -r dir1 dir2 | copy dir1 to dir2; will create directory dir2 if it doesn't exist |
cp dir/ | copy all files in dir directory to current directory |
cp -a /tmp/dir1 | copy directory dir1 with all contents to 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 directory file2 |
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 the file creation, if it is missing, create a file with the specified date and time (YYMMDDhhmm) |
cat > file | pipe standard input to file |
more file | print the contents of file |
head file | output the first 10 lines of file |
tail file | output the last 10 lines of file |
tail -f file | print the contents of 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 cf file.tar.gz files | create a tar archive with gzip compression |
tarxzf 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 file and rename to file.gz |
gzip -d file.gz | decompress file.gz to file |
bunzip2 file1.bz2 | decompresses the file "file1.gz" |
gzip -9 file1 | compress file1 with maximum compression |
rar a file1.rar test_file | create a rar archive "file1.rar" and include the test_file 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 the 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 the contents of the archive |
tar -xvf archive.tar | unzip the archive |
tar -xvf archive.tar -C /tmp | unzip archive to /tmp |
tar -cvfj archive.tar.bz2 dir1 | create an archive and compress it with bzip2 |
tar -xvfj archive.tar.bz2 | unzip the archive and unpack it |
tar -cvfz archive.tar.gz dir1 | create an archive and compress it with gzip |
tar -xvfz archive.tar.gz | unpack 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 and include several files and / or directories in it |
unzip file1.zip | decompress and unpack the zip archive |
Working with local deb packages (dpkg)
deb is the filename extension for "binary" packages for distributing and installing software on the OS of the Debian project, and others using the dpkg package management system. Deb is part of the word Debian, which in turn is derived from the words Debra - the name of the girlfriend (later wife, now ex) of Debian founder Ian Murdoch and Ian from his own name.
dpkg -i package.deb | install/update a package |
dpkg -r package_name | remove the package from the system |
dpkg -l | show all packages installed on the system |
dpkg -l | grep httpd | among all packages installed in the system, find the 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) - a program for installing, updating and removing software packages in Debian and based operating systems (Ubuntu, Linux Mint, etc.), sometimes also used in Mandrake based distributions, e.g. Mandriva, ALTLinux and PCLinuxOS. It is capable of automatically installing and configuring programs for UNIX-like operating systems, both from precompiled packages and from source codes.
apt-get install package_name | install/update a package |
apt-cdrom install package_name | install / update package from cdrom"a |
apt-get update | get updated package lists |
apt-get upgrade | update packages installed on the system |
apt-get remove package_name | remove the package installed on the system while preserving the configuration files |
apt-get purge package_name | remove the package installed on the system with the removal of configuration files |
apt-get check | check dependency integrity |
apt-get clean | delete downloaded package archive files |
apt-get autoclean | delete old downloaded package archive files |
Viewing the Contents of Files
cat file1 | print the contents of file1 to standard output |
tac file1 | output the contents of file1 to standard output in reverse order (last line becomes first, etc.) |
more file1 | paging the contents of file1 to standard output |
less file1 | page-by-page output of the contents of the file 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. The default is ten lines. |
tail -2 file1 | print the last two lines of file1 to standard output. The default is ten lines. |
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 |
cat file_original | » result.txt | the general syntax for performing actions to process the contents of a file and display the result in existing file. If the file does not exist, it will be created |
grep Aug /var/log/messages from file "/var/log/messages" | select and output to standard output the 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 standard output |
sed "/^$/d" example.txt | remove blank lines from example.txt file |
sed "/ *#/d; /^$/d" example.txt | remove blank lines and comments from example.txt file |
echo "esempio" | tr "[:lower:]" "[:upper:]" | convert characters from lowercase to the top |
sed -e "1d" result.txt | remove first line from example.txt file |
sed -n "/string1/p" | display only lines containing "string1" |
sed -e "s/*$ "example.txt | remove empty characters at the end of each line | | | sed -e "s/string1 g"example.txt | remove the string "string1" from the text without changing everything else |
sed -n "1,8p;5q" example.txt | take from the file from the first to the eighth lines and output the first five from them |
sed -n "5p;5q" example.txt | output 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 lines when outputting file contents |
cat example.txt | awk "NR%2==1" | when displaying the contents of a file, do not output even lines of the file |
echo a b c | awk "(print $1)" | display the first column. Separation, by default, by space/spaces or tab character/characters |
echo a b c | awk "(print $1,$3)" | display the first and third columns. Separation, by default, by space/spaces or tab character/characters |
paste file1 file2 | combine the contents of file1 and file2 into 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 | concatenate the contents of file1 and file2 as a table delimited by "+" |
sort file1 file2 | sort the contents of two files |
sort file1 file2 | uniq | sort the contents of two files without displaying duplicates |
sort file1 file2 | uniq -u | sort the contents of two files, displaying only unique lines (lines that occur in both files are not printed to standard output) |
sort file1 file2 | uniq -d | sort the contents of two files, displaying only duplicate lines |
comm -1 file1 file2 | compare contents of two files without displaying lines belonging to "file1" |
comm -2 file1 file2 | compare contents of two files without displaying lines belonging to "file2" |
comm -3 file1 file2 | compare the contents of two files, removing lines that occur in both files |
Convert character sets and file formats
File system analysis
Mounting file systems
Mounting a file system is a process that prepares a disk partition for use by the operating system.
The mount operation consists of several steps:
Determining the type of system to be mounted
Checking the integrity of the mounted system
Reading system data structures and initializing the corresponding file manager module (file system driver)
Setting a flag that indicates the end of the mount. When properly unmounted, this flag is cleared. If during boot the system determines that the flag is not reset, then the work was completed incorrectly, and the FS may need to be repaired
Including a new file system in the common namespace
mount /dev/hda2 /mnt/hda2 | mounts partition "hda2" to mountpoint "/mnt/hda2". 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 | forced unmounting of the partition. Used when the partition is occupied by some user |
umount -n /mnt/hda2 | unmount without adding information to /etc/mtab. Useful when a file is read-only 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 file Windows system FAT32 |
Formatting file systems
Formatting - software process marking the data storage area of electronic media located on the magnetic surface ( hard drives, 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 in creating (forming) data access structures, for example, file system structures. In this case, the possibility of direct access to the information 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)
Backup (English backup copy) - the process of creating a copy of data on a medium (hard disk, floppy disk, etc.) designed to restore data to its original or new location in case of damage or destruction.
dump -0aj -f /tmp/home0.bak /home | create a full backup of the /home directory to the 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 | sync via ssh tunnel |
rsync -az -e ssh --delete ip_addr:/home/public /home/local | synchronize local directory with remote directory via ssh tunnel with compression |
rsync -az -e ssh --delete /home/local ip_addr:/home/public | synchronize remote directory with local directory via ssh tunnel with compression |
dd bs=1M if=/dev/hda | gzip | ssh [email protected] _addr "dd of=hda.gz" | make a "cast" of the local disk to a file on a remote computer through an ssh tunnel |
tar -Puf backup.tar /home/user | create an incremental backup of the "/home/user" directory to a backup.tar file with permissions preserved |
(cd /tmp/local/ && tar c .) | ssh -C [email protected] _addr "cd /home/share/ && tar x -p" | copying the contents of /tmp/local to a remote computer via ssh tunnel to /home/share/ |
(tar c /home) | ssh -C [email protected] _addr "cd /home/backup-home && tar x -p" | copying the contents of /home to a remote computer via ssh tunnel to /home/backup-home |
tar cf - . | (cd /tmp/backup ; tar xf -) | copying one directory to another while maintaining permissions 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 an MBR (Master Boot Record) copy from /dev/hda to a floppy disk |
dd if=/dev/fd0 of=/dev/hda bs=512 count=1 | restore MBR from floppy to /dev/hda |
Disk space
df-h | displays information about mounted partitions showing total, available and used space |
ls -lSr |more | lists files and directories recursively, sorted in ascending order of size, and allows pagination |
du -sh dir1 | calculates and displays the size occupied by the directory "dir1" |
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 the files of the rpm package, 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 the files of the deb package, 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 a 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 to wav files |
cd-paranoia - "-3" | read the first three audio tracks from the disc into wav files |
cdrecord -scanbus | identify scsi channel |
Users and groups
groupadd group_name | create new group named 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 a user user1, assign it /home/user1 as a home directory, /bin/bash as a shell, include it in the admin group and add the comment Nome Cognome |
useradd user1 | create user user1 |
userdel -r user1 | delete user1 user 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 user1's account |
pwck | check the correctness of system files accounts. /etc/passwd and /etc/shadow files are checked |
grpck | checks the correctness of system account files. The file /etc/group is checked |
newgrp [-] group_name | changes the primary group of the current user. If you specify "-", the situation will be identical to the one in which the user logged out and logged in again. If no group is specified, the primary group will be assigned from /etc/passwd |
Setting/Changing File Permissions
chmod (from English change mode) - a program for changing the access rights to files and directories. The name comes from the Unix chmod OS program, which, in fact, changes the access rights to files, directories and symbolic links.
ls-lh | view permissions on files and directories in the current directory |
ls /tmp | pr -T5 -W$COLUMNS | output the contents of the /tmp directory and split the output into five columns |
chmod ugo+rwx directory1 | add permissions to the directory directory1 ugo(User Group Other)+rwx(Read Write eXecute) - all full rights. The same can be done in this way chmod 777 directory1 |
chmod go-rwx directory1 | take away from the group and everyone else all permissions to the directory directory1 |
chown user1 file1 | assign the owner of file1 to user1 |
chown -R user1 directory1 | assign recursively the owner of directory1 to user1 |
chgrp group1 file1 | change group ownership of file file1 to group1 |
chown user1:group1 file1 | change owner and owner group of file1 |
find / -perm -u+s | find, starting from the root, all files with SUID set |
Popular Meanings
400 (-r---) | The owner has the right to read; no one else has the right to do anything |
644 (-rw-r–r–) | All users have read access; owner can edit |
660 (-rw-rw--) | Owner and group can read and edit; the rest are not allowed to perform any action |
664 (-rw-rw-r–) | All users have read access; 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 do anything |
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 that 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 owner of the file |
4555 (-r-sr-xr-x) | Each user has the right to read and execute with the rights of the owner of the file |
Secure Shell Commands (ssh)
SSH (Eng. Secure Shell - "secure shell") - network protocol application layer that allows remote control operating system and tunneling TCP connections (for example, for file transfers). 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 insecure environment. Thus, you can not only work remotely on a computer through a command shell, but also transmit an audio stream or video over an encrypted channel (for example, from a webcam). SSH can also use compression of transmitted data for subsequent encryption, which is convenient, for example, for remote launch of X Window System clients.
Most hosting providers provide customers with SSH access to their home directory for a fee. This can be convenient both for working in the command line and for remotely launching programs (including graphical applications).
Process management
A process is a program that is currently running. ISO 9000:2000 defines a process as a set of interrelated and interacting activities that transform inputs into outputs. The computer program itself is only a passive collection of instructions, while a process is the direct 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 | print your current active processes |
ps-eafw | display running processes, their resources, and other useful information(once) |
ps -e -o pid,args -forest | display PID's and processes as a tree |
pstree | display process tree |
kill -9 98989 | "kill" the process with PID 98989 "to death" (without respecting data integrity) |
kill -TERM 98989 | Gracefully terminate process with PID 98989 |
kill -1 98989 | force the process with PID 98989 to reread the config file |
lsof -p 98989 | display a list of files opened by a process with PID 98989 |
lsof /home/user1 | display list open files from /home/user1 directory |
strace -c ls >/dev/null | print a list of 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 user in the system and the time of his stay in it |
lsmod | list loaded kernel modules |
free-m | show RAM status in megabytes |
smartctl -A /dev/hda | monitoring the status of the hard disk /dev/hda via SMART |
smartctl -i /dev/hda | check availability of SMART on hard drive /dev/hda |
tail /var/log/dmesg | withdraw ten recent entries from kernel boot log |
tail /var/log/messages | print the last ten entries from the system log |
Network (LAN and WiFi)
ifconfig eth0 | show eth0 network interface configuration |
ifup eth0 | activate (elevate) interface eth0 |
ifdown eth0 | deactivate (lower) interface eth0 |
ifconfig eth0 192.168.1.1 netmask 255.255.255.0 | set eth0 interface ip address and subnet mask |
ifconfig eth0 promise | switch the eth0 interface to promiscuous mode to sniff packets |
ifconfig eth0 -promisc | disable promiscuous mode on interface eth0 |
dhclient eth0 | enable eth0 interface in dhcp mode |
route-n | display local routing table |
route add -net 0/0 gw IP_Gateway | set default gateway ip address |
route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.1.1 | add static route to network 192.168.0.0/16 through gateway with ip address 192.168.1.1 |
route del 0/0 gw IP_gateway | remove default gateway ip address |
echo "1" > /proc/sys/net/ipv4/ip_forward | allow packet forwarding (forwarding) |
hostname | display computer name |
host www.linuxguide.it | resolve hostname 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 eth0 interface statistics with information such as supported and current connection modes |
netstat -tupn | displays all established network connections via TCP and UDP protocols without name resolution 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 the names of processes listening on ports |
tcpdump tcp port 80 | display all traffic on TCP port 80 (usually HTTP) |
iwlist scan | scan the air for the availability of wireless access points |
iwconfig eth1 | show eth1 wireless network interface configuration |
Microsoft Windows networks(SAMBA)
IPTABLES (firewall)
iptables is a command line utility that is a standard netfilter firewall management interface for Linux kernels versions 2.4, 2.6, 3.x, 4.x. Superuser (root) privileges are required to use the iptables utility.
iptables -t filter -nL | display all rule chains |
iptables -t nat -L | display all rule chains in NAT table |
iptables -t filter -F | clear all chains of rules 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 forward POP3 connections |
iptables -t filter -A INPUT -j LOG --log-prefix "DROP INPUT" | enable kernel logging of packets passing through the INPUT chain and prefix the message with "DROP INPUT" |
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE | enable NAT (Network Address Translate) of outgoing packets on the eth0 interface. Valid 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 | forwarding packets addressed to one host to another host |
System Information
arch | display computer architecture |
uname -r | display the kernel version in use |
dmidecode -q | show hardware system components- (SMBIOS/DMI) |
hdparm -i /dev/hda | display hard drive specifications |
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 | print the kernel version |
cat /proc/net/dev | show network interfaces and statistics on them |
cat /proc/mounts | display mounted filesystems |
lspci-tv | show in tree view PCI devices |
lsusb-tv | show in tree view USB devices |
date | display system date |
cal 2007 | display the table-calendar of 2007 |
date 041217002007.00 | set system date and time MMDDHHmmYYYY.SS (MonthDayHourMinutesYear.Seconds) |
clock-w | save system time in BIOS |
uptime | show current uptime |
w | show users online |
whoami | the name under which you are logged in |
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 inf. about disk usage |
du | display the "weight" of the current directory |
free | memory usage and swap |
where is app | possible location of app |
which app | which app will be launched by default |
System shutdown
Other useful commands
apropos …keyword | prints out a list of commands that somehow relate to keywords. Useful when you know what the program does but don't remember the command |
man ping | calling the manual for working with the program, in this case, ping |
whatis …keyword | displays a description of the actions of the specified program |
ldd /usr/bin/ssh | list libraries needed for ssh to work |
alias hh="history" | assign alias hh to history command |
find. -maxdepth 1 -name *.jpg -print -exec convert | Resizing all images in a folder, passing to ImageMagick's "convert" utility to create thumbnails of 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 Help and Program Guide
The names of programs used in commands that may come in handy need to be learned or printed, and how to use them can be found at any time by calling the help or manual (man) for the program.
To get a quick guide to the program, you need to run:
man programYou can move around with the arrow keys, and exit it by pressing the Q key. See man man for more details.
To get help with the keys, you need to run:
program -h program --help
Both options should work the same, but some software authors leave one of these keys, so try both if that.
Search by man "s
If you are not sure which command you need, try searching through the texts of the manuals.
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 the system manuals. Try:
Man -f gnome
For example, executing the whatis command will produce the same result.
More attractive man's
Gnome/Unity desktop users can use the yelp utility to provide a simple GUI by running the command in the console
Yelp man:<команда>
Users who have Konqueror installed can read and search the pages of the manual in a web browser context decorated with selected backgrounds. 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 require the following command:
This temporarily grants 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 these administrative privileges can use this command.
Commands for working with files and folders
To get into the root directory, run: cd /
To get to your home folder, type: cd ~
To move up one directory, use: cd ..
To return to the previously visited directory, use: cd -
To move through multiple directories at once, you need to write the full path of the folder you want to move to. For example, the command: cd /var/www
will move you to the /www subdirectory of /var/. And the command:
Cd ~/Desktop\table
will take you to the desktop. In this case, "\" means escaping a space.
The tilde character (~) represents your home folder. If you user, then the tilde (~) is /home /user.
The pwd ("print working directory") command lets you know which directory you are in this moment. Remember, however, that Gnome Terminal always shows the 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 the display of file size, time last change and file permissions. For example: ls~
will show everything you have in your home folder.
The cd command changes the working directory. When you first start the terminal, you will be in your home folder. To move around the file system, you need to use cd . Examples:
The cp command copies a file. For example, the command: cp text new
create exact copy file "text" and call it "new", while "file" will not disappear anywhere. To copy a directory, use the command:
Cp -r directory new
where the -r option denotes a recursive copy.
The mv command moves a file to another location, or simply renames a file. For example, the command: mv file text
will rename "file" to "text".
Mv text ~/Desktop\Desktop
will move "text" to your desktop, but will not rename it. To still rename the 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 along with sudo , the terminal also maps "~" to your home folder. However, if you enable the root session in the console with 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 removes an empty folder. To delete a folder along with all 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 the description of that command itself.
System Information Commands
Team df shows the amount of disk space used on all mounted partitions. Most useful: df -h
Because it uses Megabytes (M) and Gigabytes (G) to display, not blocks. -h means "human readable".
du displays the amount of disk space occupied by a particular folder. It can show information for all subdirectories separately or for the folder as a whole. .. [email protected]:~$ du /media/floppy 1032 /media/floppy/files 1036 /media/floppy/ [email protected]:~$ du -sh /media/floppy 1.1M /media/floppy/
S means "summary" (as a whole), and -h means "human readable" ("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 the number of processes running. To stop top , press Q .
There are also some other wonderful and very necessary utilities designed in the top style:
htop similar to top , much more powerful
if top information about active network connections, network upload/download speed
iotop information about processes performing active disk operations
uname with the -a option prints all system information, including machine name, kernel version, and other details. The most useful of these is checking the kernel version.
passwd newuser
Building a directory tree (tree)
The utility displays a directory tree in a beautifully formatted form. The tree package is in the Ubuntu repositories, so installation is a one-liner:
sudo apt-get install treeTo display a directory tree, the command should look like this:
tree -dA test- && . 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.
- alias. Assigns names you create to long commands that you cannot remember. Type alias long_command short_command.
- cd . Changes the current terminal folder. When you start the terminal, it uses your home folder. Type cd folder_address, and the terminal will work with the files that are there.
- clear. Clears the terminal window of all messages.
- history. Displays all recently entered commands. In addition, you can switch between recent commands using the Up and Down keys. If you don't want the command you typed to be recorded, precede it with a space like this: your_command.
- man. Displays a guide to programs and commands. Type man packagename or man yourcommand.
- whatis. Displays a brief description of any program. Enter the command and program name whatis package_name.
To perform many actions on the system, such as installing and removing programs, you will need administrator rights, or super root user, as it is called in Linux.
- sudo . This command will give you superuser rights. Type sudo before the desired command (for example, sudo apt upgrade) to run it as an administrator. The system will ask you for a password.
- sudo su . After this command, all commands you enter will be executed on behalf of the superuser until you close the terminal. Use it if you need to run a lot of commands with admin rights.
- sudo gksudo . The command to run as an administrator a GUI application. For example, if you want to move or change system files, type sudo gksudo nautilus (select the file manager you are using).
- sudo!! . This command will run the previously entered command with administrator rights. Useful if you typed the command without sudo .
Don't run commands you don't understand as superuser.
Installation and removal of applications in Linux is performed by package managers. On Ubuntu and the package manager it is called apt, on Fedora it is called dnf, on Arch and Manjaro it is called pacman. They download applications from network repositories, package sources. Commands should be given to them with superuser rights.
apt (Debian/Ubuntu/Mint)
- sudo apt install packagename. Install the required package.
- sudo apt-add-repository repository_address. Add a third party repository.
- sudo apt update . Update package information.
- sudo apt upgrade . Update all packages to the latest (run after apt update).
- sudo apt remove packagename. Remove unwanted package.
- sudo apt purge packagename. Remove an unnecessary package with all dependencies if you want to free up more space.
- sudo apt autoremove . Remove all unnecessary dependencies, orphaned packages and other junk.
dnf (Red Hat/Fedora/CentOS)
- sudo dnf install packagename. Install the required package.
- sudo dnf config-manager --add-repo repository_url. Add a third party repository.
- sudo dnf upgrade . Update all packages to the latest.
- sudo dnf remove packagename. Remove unwanted package.
- sudo dnf autoremove . Remove all unnecessary dependencies.
pacman (Arch/Manjaro)
- sudo pacman -S packagename. Install the required package.
- sudo yaourt -S packagename. Install the package from the AUR if it is not in the main repository.
- sudo pacman -Sy . Update package details.
- sudo pacman -Syu . Update all packages to the latest.
- sudo pacman -R packagename. Remove unwanted package.
- sudo pacman -Rs packagename. Remove unnecessary package with all dependencies.
You can install and remove multiple packages at once by simply listing them separated by spaces.
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. package manager will show all packages that start with the same name.
- kill . This command is used to force the termination of processes. You need to type kill PID_process. The PID of a process can be found by typing top .
- xkill . Another command to end processes. Enter it, then click on the window you want to close.
- killall. Kills processes with the specified name. For example, killall firefox .
- top. Displays a list of running processes, sorted by CPU usage. A kind of terminal "System Monitor".
Viewing and editing files
- cat. When the command is used on a single text file (like cat filepath), it displays its contents in a terminal window. If you specify two more files, cat path_to_file_1 path_to_file_2 , it will glue them together. If you type cat path_to_file_1 > new_file, it will merge the contents of the specified files into a new file.
- chmod . Allows you to change file permissions. May come in handy if you want to make changes to a system file.
- chown. Changes the owner of a file. Should be run with superuser rights.
- file. Displays information about the specified file.
- nano . Opens a simple text editor. You can create a new text file or open an existing one: nano file_path.
- rename . Renames a file or multiple files. The command can also be used for files by mask.
- touch. Changes the date the specified file was last opened or modified.
- wget. Downloads files from the Internet to the terminal folder.
- zip . Unpacks and compresses archives.
Creating and deleting files and folders
- mkdir . Creates a new folder in the current terminal folder or in the specified folder: mkdir folder_path.
- rmdir . Deletes the specified folder.
- rm . Deletes files. can delete as separate file, and a group corresponding to certain features.
Copying and moving files
- c.p. Creates a copy of the specified file in the terminal folder: cp file_path. Or you can specify cp destination file_path path_to_copy.
- mv. Moves a file from one folder to another. You can specify a name for the file being moved. Ironically, on Linux this command can also be used to rename files. Just specify the same folder where the file is located and a different name.
File search
- find. Search for files based on specific criteria such as name, type, size, owner, creation and modification date.
- grep. Search for text files containing specific strings. Criteria are very flexible.
- locate . Search for files and folders whose names match the query, and display their paths in the file system.
- lsblk . This command shows what disks are in 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.
- mount . Mounts drives, devices, or file systems so you can work with them. Usually devices are connected automatically as soon as you click on them in 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 run with superuser rights. To mount an existing disk or partition, type mount sdX .
- umount . Unmounts file systems. The umount sdX command will mount the file system of the external media so you can eject it.
- dd . This command copies and converts files and partitions. She 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 overwrite 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
- useradd . Registers a new user. Enter useradd username and the user will be created.
- userdel . Deletes the user's account and files.
- usermod. Changes the user account. Can move the user's home folder or set a date when the account will be locked out.
- passwd . Changes account passwords. Regular user can only change the password of its own account, the superuser can change the password of any account.
Linux Commands for Network Management
- ip . Multifunctional team for working 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 or type ip --help before using it.
- ping . Indicates whether you are connected to a network and helps you determine the quality of your connection.
And one more thing
Finally, the main Linux commands. They display a cow that can talk to you (don't ask what the developers are using).
- cowsay whatever. The cow will say what you tell her.
- fortune | cowsay. The cow will give out a smart (or not so) thought or quote.
- cowsay -l . Displays a list of all animals that can be displayed in the terminal. If you suddenly do not like cows.
- fortune | cowsay -f animal_from_list. The animal of your choice will begin to throw out quotes, sometimes appropriate ones.
- sudo apt-get install fortunes fortune-mod fortunes-min fortunes-ru . Make the whole zoo speak Russian. Without it, animals quote Twain and Wilde.
These are not all Linux commands. If you need to know in detail the options and how to use Linux commands, you can use the built-in guide. Type man yourcommand or yourcommand --help .
pwd Print the current directory.
hostname Display or change the network name of the machine.
whoami Enter the name under which I am registered.
date Display or change the date and time. For example, to set the date and time to 2000-12-31 23:57, run the command:
date 123123572000
time Get information about the time it takes for the process to complete + some other information. Do not confuse this command with date. For example: I can determine how long it takes to list files in a directory by typing:
time ls
who Determine which user is on the machine.
rwho -a Find all users connected to your network. This command requires the rwho process to be running. If not, run "setup" as superuser.
finger [username] System information about the registered user. Try: finger root
uptime The amount of time elapsed since the last reboot.
ps a List of current processes.
top An interactive list of current processes sorted by cpu usage.
uname Display system information.
free Display information from memory.
df -h (=disk space) Display information about free and used disk space (in human readable form).
du/-bh | more (= who borrowed how much) Displaying detailed information about the size of files by directories starting from the root (in a readable form).
cat /proc/cpuinfo System information about the processor. Note that the files in the /proc directory are not real files. They are used to obtain information known to the system.
cat /proc/interrupts The interrupts to use.
cat /proc/version Linux kernel version and other information
cat /proc/filesystems Print the currently used filesystem types.
cat /etc/printcap Print printer settings.
lsmod (as root) Display information about currently loaded kernel modules.
set|more Print the current values of environment variables.
echo $PATH Output value environment variable"PATH" This command can be used to display the values of other environment variables. Use the set command for a complete list.
Networking
Netconf (as root) A very good network configuration program that uses a text menu for interactive user experience.
ping [hostname] "Check for lice". Whether or not there is contact with another machine (as a parameter to the command, you can pass the machine's network name or IP address), press -C when all the required information has been obtained.
route -n Display the routing table.
ipfwadm -F -p m Configure firewall.
ifconfig (as root) Print information about the current network interfaces (ethernet, ppp, etc.) Your first ethernet card will be shown as eth0, the second as eth1, the first ppp modem as ppp0 and so on. "lo" - stands for "loopback only" network interface, which must be permanently activated. Use the appropriate options (see the output of ifconfig --help) to configure network interfaces.
ifup [network_interface_name](/sbin/ifup when running as a normal user) Activate the corresponding network interface. For example:
ifup eth0
ifup ppp0
The user can enable and disable the ppp network interface only when the appropriate permissions are set (permissions can be set during ppp configuration via "netconf")
ifdown [interface_name](/sbin/ifdown when running as a normal user). Deactivation of the corresponding network interface.
The simplest actions
ls List files in the current directory. The dir command executes the ls command.
cd [directory] Change directory.
cp [what to copy][where to copy] Copy files.
mcopy [what to copy][where to copy] Copy files when working with the dos file system (it is not necessary to mount the dos drive). For example: mcopy a:\autoexec.bat ~/junk . For more information on similar teams(mdir, mcd, mren, mmove, mdel, mmd, mrd, mformat ....) see man mtools.
mv [what to move][where to move] Move or rename file.
ln -s [link to] [link name] Create a symbolic link.
rm [files] Delete files.
mkdir [directory] Create a new directory.
rmdir [directory] Remove an empty directory.
rm -r [files and/or directories](recursive delete) Delete files, directories and their subdirectories. BE CAREFUL with this command if you have superuser rights! Until Linux has a system full recovery deleted files (if you do not use special programs indoor remote files to a special directory - a la basket for W95).
cat [filename] | more View the contents of a text file one page at a time.
less [file name] View the contents of a text file with the ability to return to previous pages. Press q when you want to exit the program. "Less" is analogous to the DOS "more" command, although very often "less" is more convenient than "more".
pico [filename] Edit a text file.
lynx View html file or WWW links using the Lynx text browser.
tar -zxvf files] Extract the tgz or tar.gz archive you pulled from the net.
find / -name "filename" Find the file named "filename". The search starts from the directory / . "filename" may contain a search mask.
pine Good text-oriented reader Email. Another similar program is called "elm". Netscape reads your emails from your Internet address, and pine allows you to view "local" mail - that is, mail sent to you by the son or cron process.
mc Run file manager "Midnight Commander" (looks like "Norton Commander" but is closer to far or dn in its capabilities).
telnet [server] Telnet to another machine. Use the machine name or its IP address. Log in with your password (you must be logged in to this remote machine). This will allow you to log into another machine and work on it as if you were sitting at its keyboard (almost no difference).
ftp [server] FTP to remote computer. This type of link is good for copying files from/to a remote machine.
minicom Minicom is a program (looks like telix or procomm for Linux).
./Program_Name Run an executable file in the current directory, which is not in the list of directories specified in the variable PATH environments.
startx Start the X-windows server and the default window manager. Similar to how you type "win" under DOS with Win3.1
xterm (in X terminal) Launch a simple terminal in the X-windows GUI. To exit it, type "exit".
xboing (in X terminal). Very cool, old - kind arkanoid.
gimp (in X terminal) Very powerful graphics editor(close to Photoshop in terms of capabilities). Takes some time to learn - very good for artists. Use the right mouse button to access the local menu.
netscape (in X terminal) Run netscape (requires separate installation of this product). Normal support for the Russian language is included in the 4.07 version of this product - so you should install this version or a newer one.
Basic Administration Commands
printtool (as root in X terminal) Configure your printer.
setup (as root) Configure the mouse, sound card, keyboard, graphics X-windows shell and system services. A very easy to use program.
alias ls="ls -Fskb --color" Create alias - an alias so that a more complex combination of commands can be run with one command. Place an alias creation in /etc/bashrc if you want these aliases to be available to all users on your system.
adduser [username] Z register a new user (you must have superuser rights). For example:
adduser ivanov
Don't forget to set the user's password next. The user directory is located in the /home/username directory.
useradd [username] Same as adduser.
userdel [username] Remove a user from the system (you must be logged in as root). The user directory and unread messages from a remote user need to be dealt with separately.
groupadd [groupname] Create a new user group on your system. It is not necessary to create a group directly on the main machine.
passwd Change password. If you are a superuser, then you can change the password of any registered user by typing the command:
passwd username
chmod [permissions][file](=change mode) Change the permissions of files owned by you (unless you are root, in which case you can change the permissions of any file). There are three ways to access a file: read - read (r), write - write (w), execution - execute (x) and three types of users: file owner - owner (u), members of the same group as the owner of the file ( g) and all others (o). You can check the current access rights in the following way:
ls -l filename
If the file is available in all ways to all users, then the following combination of letters will be opposite the file name:
rwxrwxrwx
The first three letters are the permissions for the owner/owner of the file, the second triplet are the permissions for his/her group, the next three are the permissions for the others. Lack of permission is shown as "-".;
For example: This command will allow you to set read permissions for the file "junk" to everyone (all=user+group+others):
chmod a+r junk
This command will take away the right to execute the file from everyone except the user and group:
chmod o-x junk
For receiving additional information type chmod --help or man chmod or read any Linux manual.
You can set the default permissions for the files you create with the "umask" command (type man umask).
chown [new_master][files]
chgrp [newgroup][files] Change the owner and group for a file.
You can use these two commands after you have made a copy of the file for someone else.
su (=super user) Log in as superuser (you will be asked for your password). Typing "exit" will return you to your previous user shell. The root user exists to administer the system, and the su command gives you quick access to superuser capabilities when you need them. Never log in as root, use the su command for this purpose.
Process control
Ps (=print status) Print a list of current processes with their IDs (PIDs). Use
ps axu
to display all processes running on your system that have you as the owner (this also applies to processes that are unhooked from the terminal).
fg Return a background or suspended process to an interactive (high-priority) state;
bg Make the process background. Inverse function from fg. May follow the combination z.
kill "Kill" the process. First, determine the PID of the "killed" process using ps.
killall [programname]"Kill" all processes by program name.
xkill (in an X window terminal) "Kill" the process whose window is pointed at by the cursor.
lpc (as root) Check the printer queue.
lpq List the print queue.
lprm [Job Number] Remove a job from the print queue.
nice [program name] Start a process by setting its priority.
renice Change process priority.
One of the fundamental differences between the Linux OS family and Windows OS is the leading role of the command line or terminal in system administration. For successful work with "Linux" one GUI not enough. Full control here is possible only through the terminal. And in working with the terminal, you can’t do without learning the basic Linux commands.
Linux has several hundred basic commands and their modifications. They are grouped into several categories. By location - can be command-line utilities or a built-in shell function. By frequency of use - used constantly, occasionally and rarely. By types of actions - from getting help to managing files and processes. It is the third, functional component that will become the basis for the grouping of utilities in this article.
The review contains all the most important Linux commands that can be useful for administering the Linux OS. The article is designed for both beginners and advanced users who are already familiar with the basic functionality of the terminal. This kind of cheat sheet can be safely bookmarked by anyone who wants to extract the maximum of useful properties from Linux and increase their productivity several times.
Help / Documentation
man
(Manual). Shows instructions to Linux programs and commands. To get the manual for the program, type:
Man program_name
For command instructions, type:
Man command_name
whatis
Displays short description programs. Example:
Whatis program_name
whereis
Shows full path to the executable file and other program files. Example:
Whereis program_name
Also gives information about program-related help information.
file
Shows what type is the file. The peculiarity of Linux is that working files may not have an extension. Therefore, the user may have problems identifying the files that this command removes.
–help
All the necessary information about the team will be available if you type:
ProgramName --help
whoami
The command shows the actual user ID(UID).
TAB
Shows options command completion. Pressing the tab key after a certain command or a sequence of them displays a hint with options for the possible continuation of the command.
ctrl+r
This keyboard shortcut helps to launch reverse lookup for all parameters associated with the specified command. It suffices to indicate keyword For search. There is a serious minus - at a time you can see only 1 result. The combination Ctrl + C will help you exit the reverse search mode.
Superuser rights
Many basic Linux commands, such as installing programs or creating files on the root system, require root or superuser privileges to execute. Application this mode brings serious changes to the operating system, so you need to understand exactly how the running command will work.
Ways to get root permissions in Linux
- Login as superuser in the virtual console by entering the username and password of the root user.
- One-time switching to the superuser role in the terminal using special utilities.
Let's talk about the second option in more detail.
sudo
(Super User Do). Allows execute commands with superuser rights. Before entering root administrator mode, the system will prompt for a password and login for root. Example:
sudo commandname
sudo su
The tool is used when you need to run several"superuser" commands. All of the following commands you enter will run in superuser mode until the command prompt is closed.
sudo gksudo
Launches applications on behalf of the superuser, using not a terminal, but GUI. In the Kubuntu distribution, the name of this command is slightly different - sudo kdesudo .
sudo!!
The command is used if you need to restart from as root already given(as a normal user) command.
The maximum performance of Linux applications depends on the correct selection of the platform for the OS. Powerful will provide the Internet resource with stable operation and space for development.
File and directory management
ls
(List). With this utility, you can see what is in the folder. Without specifying a specific path, shows the current directory. If the path is specified, then the transition will be made to its final directory. To display the catalog as a list with additional explanatory information, type:
To show hidden files:
ll
View Command directory contents. A more modern alternative to this utility, ls -l, may not work on all Linux distributions.
cat
(Concatenate / Catenate). Dual purpose team. Shows on screen what does the file contain or standard input. Also to "glues" several files transferred in a row into one. If you want to see the contents of one file, enter:
Cat filename
If you need to find out the contents of several files in a row:
Cat file_#1 file_#2 file_#3
To "glue" the files, enter:
Cat file_#1 file_#2 > file_#3
To set the desired number of lines in the shown:
cd
(Change directory). Changes current catalog, in which the terminal is running on the specified. When the terminal is launched, it defaults to the root directory, which you can return to by typing:
To specify a different folder for working with files, you need to enter:
cd folder_address
To move up the directory tree one level up, type:
To return to the previous directory:
&&
The double ampersand is not a full command, but a control operator. It is designed to perform sequential a number of teams. In order for the terminal to execute the commands one after the other, you need to separate them as follows:
Team_#1 && Team_#2 && Team_#3
The number of commands in this sequence is not limited.
mkdir
(Make Directory). Creates new directory. You can also create complete structure subdirectories, if you enter a combination:
mkdir -p
cp
(Copy). A utility that allows copy file or directory. Copying files and directories. To copy recursively, i.e. include all subdirectories and files in them, you need to add to the command:
And if you need to supplement recursive copying with saving all attributes, information about the owner and a timestamp, add the "archive" option -a to get:
Cp-r-a
mv
(Move). This command in Linux is simultaneously responsible for moving and renaming file or directory. When renaming the file, it moves to the same folder, but already named in a new way.
rm
(Remove). Responsible for removal folders and files. The rm operator should be used with extreme caution. In Linux, files are not deleted to the recycle bin, from where they can be restored, but are erased forever. For recursive deletion, use the combination:
ln
Linux Link Types
- symbolic (-s ) - pointing to the address of a file or folder without metadata;
- hard or hard (-P ) - contains information about the physical address on the disk where the file is stored.
You can remove a link in Linux using the -f attribute.
chmod
(Change Mode). Changes access permissions to the file. Access refers to the classic triad: reading r, modifying w, and running x. General form:
Chmod permissions filename
In this case, "permissions" can be indicated by an alphabetic, symbolic (rwx) or numeric code. In addition, this variable can include owner information (u / g / o / a ) and rights operations (+ / – / = ).
Popular permission combinations for the chmod command
Type of permission | Character code | Numeric code |
No clearance | — | 0 |
Reading | r– | 4 |
Change | -w- | 2 |
launch | -x | 1 |
Launch + Change | -wx | 3 |
Read + Run | r-x | 5 |
Read + Modify | rw- | 6 |
Launch + Change + Launch | rwx | 7 |
chown
(Change Owner). Command for change of ownership file and its group. To change ownership, use the syntax:
Chown new_owner filename
To change the group of a file:
Chown newgroup filename
If you need to change both parameters:
Chown new_owner:new_group filename
The command can only be used with superuser rights. To change the owner/group recursively add:
Chown-R
chgrp
(Change Group). Changes group file. Unlike chown, this command allows you to change groups, only those who are members of it.
dd
(Dataset Definition). Allows copy data on a binary level from one place to another. The data can be of any size - from a CD/DVD image to an entire hard drive.
The utility moves blocks of data from the specified source - if filename to destination - of filename , which can be a device or a file. The cp utility is used to copy multiple files.
This command must be handled with extreme care, as evidenced by its alternative name "Data Destroyer". A data entry error can easily cause data to be lost on the disk.df
(Disk Free). Gives complete information about free space on disk. The analysis includes enumeration of file systems of mounted partitions, overview of used and free space on disk. For a more convenient output of information, it is better to use a combination:
du
(Disk Usage). Allows determine the size file or directory. Used in conjunction with additional operators:
- df -h - presents size data in a human-readable format;
- df –s - gives the required minimum of data;
- df -d - sets the recursion depth for directories.
mount / umount
Linux commands for installation and disconnection any file systems - from a CD-ROM and a USB flash drive to OS kernels. The filesystem type is usually determined by the command itself by reading the superblock. The option is used only with superuser rights.
Navigation
find
Implements Search in the file system, files and folders. Additional commands can be run on search results.
pwd
Displays on screen current directory.
clear
Team complete cleaning terminal window deletes all previously displayed messages.
history
Shows previously introduced command user. You can navigate through the list of entered commands by pressing "Up" and "Down" on the keyboard.
locate
Quick search files against the updatedb database for filename patterns. This database works with a snapshot of the file system, which greatly speeds up the search process. But there is also a significant downside. The accuracy of the search depends on how up-to-date the file system data is in the current version of the snapshot.
zcat / zless / zmore
Utilities for viewing compressed files. With the help of zcat, you can find a list of compressed files, zless lists them page by page with the ability to scroll forward and backward, and zmore - only forward.
;
The semicolon is another operator for sequential launch multiple commands on one line. If you want the commands to be executed in parallel, use the statement like this:
(team_#1 &); (team_#2 &); (team_#3 &)
Network management
ip
(Internet Protocol). The utility displays a complete list of parameters for network settings. Among them:
- link - network device;
- address - IP address of the network device;
- monitor - device monitoring;
- route - routing;
- tunnel - tunneled.
Each of the displayed objects can be modified using additional commands: add , change , del , save , etc.
ping
The team checks Availability and quality of Internet connection.
nethogs
Utility network activity monitoring devices in the system. To set the network interface, enter:
Nethogs -i
traceroute
Utility Internet connection tracking, tracking the routes of data packets in TCP / IP networks. A better tool for tracking down network connectivity problems than the ping command mentioned above. Runs only with superuser rights.
Working with processes
kill/xkill/pkill/killall
Command variations for completion of operations. The main difference between them is the way of identification.
- kill - Terminates an operation by finding it through the process ID (PID).
- xkill is a graphical way. After entering the command, the cursor turns into a cross, which, when clicked on the window of an open process, stops it;
- pkill - Kills a specific process by finding it by name.
- killall - Kills all processes with the specified name.
Ctrl+C
This keyboard shortcut is another fast way to complete execution of any process in the Linux terminal.
Ctrl+Z
The combination puts any process running in the console pause. You can run it again by typing % .
ps/grep
(Process Status / Process-ID Global Regular Expressions Print). Commands find by specified parameters and display information about active processes. Most affordable way find the process id (PID). The pstree modification shows the entire list ("tree") of executable processes.
top/htop/atop
(Table of Processes). Three options for a command that calls a console program monitoring active processes in system. The information is displayed in the form of a table with a list of processes in real time. It is recommended to use the last two modifications of the program - they have more features and advanced functions.
crontab
Execute Cron (Command Run ON) - scheduled tasks in linux.
time
- real - total execution time;
- user - how much time the user took from the CPU;
- sys - how much CPU time was spent by the system.
Minimizing the execution time of a Linux OS process will help! A one-stop solution at an affordable price!
Working with archives
gzip
Creates archives with compressed files. The archive file will have a .gz extension.
gunzip
Team- unpacker for zip archives. Extracts compressed files and removes the .gz archive file.
tar
Saves archive files and directories with .tar extension. Convenient tool for creating backups or secure data archiving.
user management
useradd/userdel/usermod
Teams account management users. Allows you to add, delete and edit user profiles. Example:
Useradd username.
passwd
Allows change account passwords. A normal user can only change the password associated with their username: passwd username. In superuser mode, you can blindly reset all user passwords on the system.
Work with text
Ctrl+A / Ctrl+E
Shortcut keys go to start(A) and the end(E) lines.
Ctrl + Shift + C / Ctrl + Shift + V
This keyboard shortcut in Linux will allow you to quickly copy(C) and insert(V ) text in terminal.
more / less
Two commands for relief viewing large texts, which do not fit on one terminal emulator screen. Because functionally the commands are the same, but less is newer and supports more options, it is recommended to use it.
head / tail
A pair of complementary commands for viewing on one screen beginning and end of text. The head command produces the 10 (by default) first lines of text, tail the last. The number of lines in both cases is changed with the -n argument. The -f operator allows you to monitor changes in a file on the screen. To display the file log (log) in real time, enter the command:
tail-nf,
To track the logs of several files, a modification of the command - multitail is used.
grep
(Global Regular Expression and Print). Looking for text according to the given template. This is very useful when you need to analyze the work of a team that is accompanied by a large amount of textual information. The template can be filled with a string or regular expression. Example:
Alias old_name new_name
sort
Sorting textual information on the given indicators. Additional variables allow:
- -n - sort lines of text by numeric value;
- du - by size;
- -r - apply reverse sorting;
- -u - remove duplicates when sorting.
wc
(Word Count). Program for calculation of the given parameters in the text. Counts indicators such as characters, words, strings, and bytes.
diff
(Difference). Produces line by line comparing two text files, deducing the differences between them. Work algorithm:
Diff file_#1 file_#2
Differences between the two versions of files are marked with symbols such as:
- c - changed lines;
- d - deleted lines;
- a - new lines.
User environment
su / sudo
(Switch User / Substitute User & Do). Two commands to start processes on behalf of another user without terminating the current session. Using su defaults to the root user. The sudo command can not only activate the superuser mode (as mentioned above), but also execute a command on behalf of another user without actually switching to it. Therefore, the second option is considered safer.
date
Linux team reporting time information. Separate variables can set a convenient output format and the number of displayed parameters, up to milliseconds.
alias
Command for creating synonyms names of non-replaceable commands to shorten them. It changes the long name to a user-friendly short name or an abbreviation. Example:
Alias old_name new_name
The same technique is perfect for correct typographical errors in teams. The unalias command will help you undo the action of the rename utility.
uname
A utility that outputs operating system information. Without additional parameters, it will give only the name of the kernel. To get all possible system information, type:
uptime
Shows uptime - continuous work time systems.
sleep
Sets sleep timer systems.
yes
Autocomplete utility consent fields in a command or script. Enter: yes command_name and you don't have to do manual confirmation when it is required by the user interaction scenario.
Package managers
Package managers (PMs) in Linux are responsible for installing, updating, and removing applications. The principle of their work is downloading software packages from their own network repositories. These utilities work only with superuser rights. For various Linux distributions there are versions of PM.
apt
PM for Debian, ubuntuandmint
sudo apt install packagename
To remove an application:
sudo apt remove packagename
dnf/yum
The two most common PMs for operating systems red hat, Fedora and CentOS. To install the application, enter:
sudo dnf install packagename
To delete:
sudo dnf remove packagename
pacman
Distribution package manager Arch and Manjaro. To install the application, enter:
sudo pacman -S packagename
To remove an application:
sudo pacman -R packagename
Conclusion
A complete list of commands for Linux distributions is more of a book than a single article. However, in this review we have tried to collect the most important of them. These commands are guaranteed to be useful both for everyday tasks and for unlocking the advanced features of this operating system.
Everyone has it Linux user there is a list of must have commands. Surely you have something to add to this review? Share your favorite Linux commands in the comments!
Do you want the operating system to work like a Swiss watch? Reliable and powerful deployment platform for any Linux distribution - !
Alekseev Igor Gennadievich,
Brantsevich Petr Yulyanovich
“OPERATING SYSTEMS and SYSTEM PROGRAMMING”
teaching aid for students of the specialty
« Software information technologies"
UDC 004.04 (075.8)
BBK 32.973 i 73
Reviewer:
A47 Alekseev I.G. Teaching aid Operating systems and system programming: for students. specialist. "Information technology software" / I.G. Alekseev, P.Yu. Brantsevich - Minsk: BSUIR, 2009. - 73 p.
ISBN 985-444-No.
The manual discusses the main commands of the operating UNIX systems, designed to work with files and directories, as well as to create processes and organize interaction between them. The structures of laboratory work on the course "OSiSP" are 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 Commands of UNIX OS............................................... ............. four
2. Laboratory work.............................................. ......................... 7
Laboratory work№1 Work in OS UNIX/Linux,
BASH interpreter .................................................. ............................................. 7
Lab #2 Working with UNIX Files and Directories.... 12
Lab #3 Processes in UNIX/Linux .............................................. 17
Lab #4 Using Signals in UNIX/Linux ….. 21
Lab #5 Using Pipes in UNIX/Linux …… 26
Lab #6 Threads in UNIX/Linux ……………………… 33
Lab #7 Semaphores in UNIX/Linux …………………… 36
Lab #8 Using Shared Memory in
OS UNIX/Linux …………………………………………………………………… 39
Literature................................................. ................................................... 42
BASIC UNIX COMMANDS
Operating system OS linux based on OS UNIX and largely has a 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 at the same time (6 in the text mode of the console and 1 in the graphic mode), switching between users is carried out by pressing the keys:
.
In table. 1 shows the main commands of the system
Table 1
Team | Arguments/keys | Example | Description |
dir | catalog | dir 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 | Deletes a directory |
rm | file | rm myfile1 | Deletes a file |
mv | file new name | mv myfile1 myf1 | Renaming a file |
cat | file | cat 1.txt | Output file to console |
cd | directory name | cd home | Navigating directories |
grep | (see man) | grep "^a" "words.txt" | Finding a line in a file |
kill | process pid | kill 12045 | Kills a process |
top | Prints a list of processes to the console | ||
htop | Prints a complete list of running processes to the console | ||
su | Change 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 | Copy by byte |
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 | File search |
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 have support journaling . Journaled the file system first writes the changes it will make to separate part file system ( magazine ) and only then makes the necessary changes to the rest of the file system. After successful completion of all transactions, records are deleted from magazine . This ensures better system integrity and reduces the chance of data loss. It should be noted that linux supports access to Windows -sections.
File system linux has only one root directory, which is denoted by a slash ( / ). In the file structure linux no disks A, B, C, D ...., but there are only directories. AT linux distinguish between uppercase and lowercase letters in commands, file and directory names. AT Windows Each file has only one name, linux there may be many. It - " tough » links that point directly to the inode of a file. 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 points ( .. ) denote the parent directory of the current worker.
- tilde ( ~ ) denotes 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 operation of the system. Catalog /bin does not contain subdirectories. |
/boot | Here are the core of the system itself (file vmlinuz-...) and the files needed to load it. |
/dev | Catalog /dev contains device files (drivers). |
/etc | This is a catalog configuration files, i.e. files containing information about system settings (for example, program settings). |
/home | Contains the home directories of system users. |
/lib | Libraries are located here (functions needed by many programs). |
/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 home directory of the system administrator. |
/sbin | Contains executable programs, like a directory /bin. However, only the system administrator can use the 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 programs terminate. |
/usr | A directory for most programs that don't matter to boot the system. The structure of this directory actually duplicates the structure of the root directory. |
/var | Contains data that was received 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