Usefull commands Version 2025.7.9. man command - display documentation about command. Find string in documentation: man -K string info - read info documents. whatis - show one line command description. Find commands by pattern: whatis -w 'pattern' List all basic commands: whatis -s 1 -w '*' List all commands: whatis -s 1,8 -w '*' 1 is section for basic commads. 8 is section for administrative commads. cat - concatenate files and print on the standard output. cd - change the working directory. ls - list directory contents. pwd - print name of current directory. cp - copy files. mv - move files. mkdir - make directories. bc - calculator. date - display the date and time. date -I - displays date that is useful when create file with name as current date. runlevel - output previous and current runlevel. fdisk - manipulate disk partition table. free - display amount of free and used memory in the system. gcc - C compiler. g++ - C++ compiler. grep - search a file or stdin for a pattern. look - display lines beginning with a given string. head - output the first part of files or stdin. tail - output the last part of files or stdin. seq - print a sequence of numbers. iconv - convert text from one character encoding to another. Convert file from cp1251 to utf8: iconv -f cp1251 -t utf8 file_name -o file_name md5sum - print or check MD5 checksums. umount - від’єднати файлову систему. env - show environment variables. pgrep, pkill - look up or signal processes based on name and other attributes. read - read a line from stdin. sleep - suspend execution for an interval. sort - sort lines of text files (or stdin). tee - read from stdin and write to stdout and files. top - display Linux tasks. xset - user preference utility for X. nsloookup - запитати IP-адресу в DNS, вивести адресу DNS. file - determine file type. ldd - print shared library dependencies. Get string md5sum: md5sum <<< 'string' Get file md5sum: md5sum file_name Generate initramfs image for current kernel: dracut --force Switch monitor to standby mode: xset dpms force standby Show command execution time: time command Compare files: cmp file1_name file2_name Compare files: diff file1_name file2_name cmp and diff can also compare binary files. Compare directories: diff -r directory1_path directory2_path Find wifi access points: iwlist scan Check mail sending: echo 'Check.' | mail -s Check sergiyvovk69@gmail.com Connect to FTP or SFTP server: lftp -u user_name server_address Connect to FTP server: ftp server_address Show devices space usage and mount points: df -h Show specified device space usage: df -h device_or_mount_point Show current directory size: du -hs Show directory size: du -hs directory Show total size of files or directories: du -ch file1/directory1 file2/directory2 ... Show messages from kernel: dmesg Print uptime and load: uptime Make symlink: ln -sv target link_name Make symlink in current directory: ln -sv target Make symlinks in directory: ln -sv targets_list directory Show current locale: locale List locales: locale -a Run application with specified locale: LANG="locale_name" application The locale for user may be set in ~/.bashrc file. Example: export LANG="uk_UA.utf8" fsck - check and repair a Linux file system. Check ext2/3/4 file system: sudo e2fsck -v device Force check ext2/3/4 file system: sudo e2fsck -v -f device Check blocks on ext2/3/4 file system: sudo e2fsck -v -f -c device Check fat32 file system: sudo fsck.vfat device Check ntfs file system: sudo ntfsck device Check xfs file system: sudo xfs_repair -v device Check exfat file system: sudo exfatfsck device Reboot computer: shutdown -r now Power off computer: shutdown now Encode string to base64: <<< 'string' base64 Decode string from base64: <<< 'base64_string' base64 -d Encrypt string by password: <<< 'string' openssl enc -e -a -aes-128-ctr -nopad -nosalt -k password Decrypt string: <<< 'crypted_string' openssl enc -d -a -aes-128-ctr -nopad -nosalt -k password Опції -nopad, -nosalt не обовязкові але дозволяють отримати компактніший вивід. Отримати список алгоритмів шифрування: openssl enc -ciphers -aes-128-ctr це один з аглоритмів шифрування. Завдяки -a вивід буде стрічкою а не двійковий. Якщо -k password не задати, пароль запитається в терміналі. Encrypt file: openssl enc -e -aes-128-ctr -k password -in input_file -out output_file Decrypt file: openssl enc -d -aes-128-ctr -in input_file -out output_file Some openssl enc command options: -help Display options summary -e Encrypt -d Decrypt -a Base64 encode/decode -base64 Same as -a -in infile Input file -out outfile Output file -k value Passphrase -kfile infile Read passphrase from file Generate key: openssl rand -base64 length Generate key to file: openssl rand -base64 -out file length Generate hex key: openssl rand -hex length Create disk image: dd if=device of=file.img Create disk image, skip errors: dd if=device of=file.img conv=noerror Write image file to disk: dd if=file.img of=device Create 10 * 2 mb file with zero bytes: dd if=/dev/zero of=file_name bs=10M count=2 Create file with 512 zero bytes: dd if=/dev/zero of=file_name bs=512 count=1 Create file with 512 random bytes: dd if=/dev/urandom of=file_name bs=512 count=1 Mount image file: mount -o loop file.img /mnt/image Write the iso image with linux to usb stick: umount /dev/sdX* sudo dd if=iso_image_file of=/dev/sdX bs=8M status=progress oflag=direct X is the usb stick letter. Get directory checksum: rhash -r --md5 directory | sort | md5sum Create 10 gb qcow2 disk image: qemu-img create -f qcow2 file_name.qcow2 10G Convert qcow2 disk image to raw: qemu-img convert -f qcow2 -O raw input_file.qcow2 output_file.img Convert raw disk image to qcow2: qemu-img convert -f raw -O qcow2 input_file.img output_file.qcow2 Show firewall settings: sudo firewall-cmd --list-all Enable port: sudo firewall-cmd --permanent --add-port=port_number/tcp sudo firewall-cmd --reload List swaps: swapon --show Activate swap: swapon device_or_file Dectivate swap: swapoff device_or_file Примітка. Live Fedora може підключити swap /dev/mapper/fedora-swap автоматично якщо він існує. The example of creating swap file: dd if=/dev/zero of=/swapfile bs=10M count=50 mkswap /swapfile chmod -v 600 /swapfile Show ext2/3/4 file system label: e2label device Set ext2/3/4 file system label: e2label device label Show lines that is in list1.txt but not in list2.txt: diff list1.txt list2.txt | grep '^< ' | sed 's/^< //' watch - repeat command and show output. screen - screen manager with VT100/ANSI terminal emulation. ctrl a ?: довідка про клавіши. ctrl a c: запустити нову копію bash. ctrl a d: відключитись від програми screen. ctrl a ": показати список запущених програм через який можна перейти на іншу програму. ctrl a 0-9: перейти на програму під введеним номером. C-a k: destroy current window. Запустити команду у програмі screen: screen команда Запустити команду у програмі screen і відключитись від неї: screen -d -m команда Показати список сеансів: screen -ls Перейти до сеансу: screen -r імя_сеансу Перейти до останього сеансу: screen -R Виконати на сервері ssh команду у програмі screen: ssh -t імя_користувача@адреса_серверу 'screen команда' Після цього для відключення від серверу ssh можна натиснути ctrl a d. Перейти до останього сеансу програми screen на сервері ssh: ssh -t імя_користувача@адреса_серверу 'screen -R' Job control: Зупинити процес і поверутись в командний рядок можна клавішами ctrl + z. Запустити команду в фоні: команда & Продовжити процес в фоні; bg [ %номер ] Продовжити процес в фоні; %номер & Повернутися до процесу: fg %номер Повернутися до процесу: %номер Повернутися до останього процесу: fg Отримати список запущених задач: jobs nohup - run a command immune to hangups, with output to a non-tty. Запустити команду в фоновому режимі так щоб вона не завершилась після закритя терміналу або завершення скрипту можна таким чином: nohup команда > /dev/null & Run program and return to terminal: (program &> /dev/null &) The program will not be closed if user will close the terminal. The same effect may be achieved by nohup command. Scan current directory for virus: clamscan -ir Scan directory for virus: clamscan -ir directoty_path Update clamav virus database: sudo freshclam scp — remote file copy program. Generate ssh key: ssh-keygen -t rsa Generate private ssh key to file: ssh-keygen -t rsa -f file-name The public key will be saved to file-name.pub. Specify port for ssh: ssh -p port user@host Specify private ssh key file for ssh: ssh -i key-file user@host Add ssh key: ssh-copy-id user@host ssh-copy-id -p port user@host ssh-copy-id -i key-file user@host key-file це публічний ключ. Якщо приватного ключа немає в одній папці з публічним ключем, можна використати команду: ssh-copy-id -f -i key-file user@host The public ssh key file can be added to the end of ~/.ssh/authorized_keys file. Sample: cat key-file >> ~/.ssh/authorized_keys Run graphic program by ssh: ssh -X user_name@server_address program_name Sample of SSH tunel creating: ssh -L 5432:localhost:5432 -N -f -l simple_user vps2.happyuser.info ssh -L 5432:localhost:5432 -N simple_user@vps2.happyuser.info ssh -L 5900:localhost:5900 -N -f -l lim -p 3645 178.95.250.72 -N : do not execute command on remote host. -f : background mode. -l : login. -p : port. Sample of reverse SSH tunel creating: ssh -R 9080:localhost:9080 -N -l simple_user vps2.happyuser.info ssh -R 9080:localhost:9080 -N simple_user@vps2.happyuser.info An access to port 9080 on a server will be local. Sample 2 of reverse SSH tunel creating: ssh -R '*:3005:localhost:3000' -N -l gateway vps2.happyuser.info ssh -R '*:3005:localhost:3000' -N gateway@vps2.happyuser.info ssh -R vps2.happyuser.info:3005:localhost:3000 -N gateway@vps2.happyuser.info ssh -R 95.85.37.18:3005:localhost:3000 -N gateway@95.85.37.18 This allows external access to a server on port 3005 which will be redirected to a local port 3000 and requires "GatewayPorts yes" or "GatewayPorts clientspecified" in /etc/ssh/sshd_config on a server. Sample of how to measure the download speed of SSH channel: ssh simple_user@vps2.happyuser.info cat /dev/urandom | dd of=/dev/null status=progress Sample of how to measure the upload speed of SSH channel: < /dev/urandom ssh simple_user@vps2.happyuser.info dd of=/dev/null status=progress Split string sample: grep -Eo '[^,]+' <<< 'string1,string2,string3' Each element will be get as separate line. Get first element: grep -Eo '^[^,]+' <<< 'string1,string2,string3' Get last element: grep -Eo '[^,]+$' <<< 'string1,string2,string3' Get list element sample: cut -d, -f3 <<< 'string1,string2,string3,string4' Replace spaces by \n: tr ' ' '\n' <<< '1 2 3 4 5' Delete spaces in string: tr -d ' ' <<< '1 2 3 4 5' Get subexpression sample: sed -r 's/^.*:(.*),.*$/\1/' <<< 'string1:string2,string3' Enclose strings between quotes: echo -e "string 1\nstring 2\nstring 3" | sed "s/.*/'&'/" The detailed samples about sed is in sed_sample.sh file. Show hexadecimal values of string bytes: echo -n "string" | od -t x1 Redirect standard output and standard error to /dev/null: command &> /dev/null Create iso image: genisoimage -R -o iso_file_name directory_path Look for useable CD/DVD devices: wodim --devices dev='/dev/cdrom' Print CD/DVD drive capabilities: wodim -prcap dev='/dev/cdrom' Print CD/DVD drie inquiry information: wodim -inq dev='/dev/cdrom' Blank the entire CD/DVD-RW disk: sudo wodim -v blank=all -eject dev='/dev/cdrom' Minimally blank CD/DVD-RW disk: sudo wodim -v blank=fast -eject dev='/dev/cdrom' Record CD/DVD from iso image: sudo wodim -v -eject dev='/dev/cdrom' iso_file_name Record CD/DVD from directory: genisoimage -R directory_path | wodim -v fs=6m speed=2 dev='/dev/cdrom' - Eject CD/DVD: eject /dev/cdrom Example of connection to VNC server via SSH tunnel: vncviewer -via taras@188.226.157.20 localhost::5901 Show information about video or audio: ffprobe input_file Encode video or audio: ffmpeg -i input_file output_file Имя вихідного файлу залежить від його розширення. To specify the target bitrate for video and audio, use the -b:v and -b:a options, respectively. You can use abbreviations like K for kBit/s and M for MBit/s. Example: ffmpeg -i input.mp4 -b:v 1M -b:a 192K output.avi Install tesseract: sudo dnf install tesseract tesseract-langpack-ukr gimagereader-gtk The gimagereader-gtk is frontend for tesseract. Recognize english text on the picture: tesseract picture.png stdout Recognize english text on the picture and output result to out.txt: tesseract picture.png out Recognize ukrainian text on the picture: tesseract picture.png stdout -l ukr Recognize english and ukrainian text on the picture: tesseract picture.png stdout -l eng+ukr Set host name: hostnamectl set-hostname host_name Get the file from internet and write to standart output: curl -s file_address Download the file from internet: curl -o file_name file_address Execute string as JavaScript: node -e "string" Execute string as PHP: php -r "string" Check ports: netstat -atnp|grep LISTEN List estabilished and listened TCP sockets: ss -atn List estabilished and listened TCP sockets with its processes: ss -atnp List estabilished TCP sockets: ss -tn List listened TCP sockets: ss -ltn -a : estabilished and listened sockets. -l : listened sockets. -t : TCP sockets. -p : show sockets processes. -n : show ports numbers instead of services names. nmap 192.168.1.2-254 Scan ports: nmap -p1-65535 localhost Find files by name: locate pattern Find files by name, ignore case: locate -i pattern find - find files in current directory. find directory - find files in directory. find -iname '*.txt' - find files with txt extension in current directory. find directory -iname '*.txt' - find files with txt extension in directory. find sample by "or" operator: find -name '*.jpg' -o -name '*.png' find -name pattern - case sensitive search by file name in current directory. mkfs - build a Linux filesystem. Format partiion to ext4 file system: sudo mkfs.ext4 -L label device Format partiion to fat32 file system: sudo mkfs.vfat -n label device Format partiion to ntfs file system: sudo mkfs.ntfs -L label device -f : fast format. Format partition to exfat file system: sudo mkfs.exfat -n label device mount - приєднати файлову систему. Показати список зионтованих файлових систем: mount без опцій. Mount ext4 filesystem: mount -t ext4 device directory_path Mount ext4 filesystem for read only: mount -r -t ext4 device directory_path Mount ftp: curlftpfs ftp://user:password@host directory Unmount ftp: fusermount -u directory Sample: mkdir /tmp/android-ftp curlftpfs ftp://android:android@192.168.1.29:2221 /tmp/android-ftp fusermount -u /tmp/android-ftp Show EFI boot configuration: efibootmgr Shedule next boot configuration: efibootmgr -n configuration_number zenity - display GTK+ dialog. Display file selection dialog: zenity --file-selection Display notification: zenity --notification --text='Nnotification.' Display info dialog: zenity --info --text='Message.' Display error dialog: zenity --error --text='Message.' Display warning dialog: zenity --warning --text='Message.' Display question dialog: zenity --question --text='Question.' Display password dialog: zenity --password Display text entry dialog: zenity --entry --text='Message.' ------------------------------------------------------------------------------------------------- Archivators Create archive: tar cvzf ArchiveName.tar.gz file1/directory1 ... tar cvjf ArchiveName.tar.bz2 file1/directory1 ... tar cvJf ArchiveName.tar.xz file1/directory1 ... zip AcrhiveName.zip file1 ... zip -r AcrhiveName.zip directory1 ... 7z a ArchiveName.7z file1/directory1 ... xz має найбільше стиснення. Якщо в bzip2, gzip чи xz не задати імя файлу то вони працюють з стандартним вводом/виводом. gzip не підходить для файлу розміром > 4 гб. bzip2, gzip and xz options: -1 ... -9 - set the compression level. -1 - fast compression. -9 - best compression. Compression levels for xz are -0 ... -9. -0 - fast compression. -9 - best compression. -c - write output on standard output; keep original files unchanged. -d - decompress. -k - keep (don't delete) input files during compression or decompression. -T 0 - use all processor cores during compression by xz. -T number - use specified number of processor cores during compression by xz. -t - test. Check the compressed file integrity. -v - verbose mode. xz displays the progress. Backup device to xz archive: dd if=DeviceFile status=progress | xz -0 -T 0 > ArchiveName.xz Use -0 and -T 0 if need. Restore device from xz archive: xz -dc ArchiveName.xz | dd of=DeviceFile status=progress Backup device to bz2 archive: dd if=DeviceFile status=progress | bzip2 -1 > ArchiveName.bz2 Use -1 if need. Restore device from bz2 archive: bzip2 -dc ArchiveName.bz2 | dd of=DeviceFile status=progress Compress to bz2 archive and delete file: bzip2 FileName Decompress and delete bzip2 archive: bzip2 -d ArchiveName.bz2 Compress to gz archive and delete file: gzip FileName Decompress and delete gz archive: gzip -d ArchiveName.gz Compress to xz archive and delete file: xz FileName Decompress and delete xz archive: xz -d ArchiveName.xz unxz ArchiveName.xz Decompress xz archive to stdout: xzcat ArchiveName.xz 7z використовує одночасно всі ядра процесору. Compress standart input to 7z archive: command | 7z a -si ArchiveName Extract 7z archive to standart output: 7z x -so ArchiveName File split example: 7z a -v20m zombi.7z zombi.avi Test zip archive: unzip -t AcrhiveName '*' Test 7z archive: 7z t ArchiveName Check the gz archive integrity: gzip -tv AcrhiveName Check the bz2 archive integrity: bzip2 -tv AcrhiveName Check the xz archive integrity: xz -tv AcrhiveName List the content of a zip archive: zipinfo ArchiveName List the content of a zip archive with one file per line showing: zipinfo -1 ArchiveName List the content of a tar archive: tar tf ArchiveName List the content of a 7z archive: 7z l ArchiveName List the content of a rar archive: unrar l ArchiveName Unpack zip archive to current directory: unzip ArchiveName Unpack zip archive to specified directory: unzip ArchiveName -d DirectoryPath Unpack tar.gz archive to current directory: tar xvzf ArchiveName.tar.gz Unpack tar.bz2 archive to current directory: tar xvjf ArchiveName.tar.bz2 Unpack tar.xz archive to current directory: tar xvJf ArchiveName.tar.xz Extract 7z archive to current directory: 7z e ArchiveName Extract rar archive to current directory: unrar e ArchiveName ------------------------------------------------------------------------------------ Processes ps - report a snapshot of the current processes. ps command samples: ps -e ps ax ps axu ps x ps -eo args --sort args ps axo args --sort args ps -eo comm ps -eo comm,user ps -eo comm,%cpu --sort %cpu ps -eo %cpu --no-headers | tr -d ' ' | paste -s -d + | bc ps -C Xvnc -o args ww ps uU simple_user Show information about process with pid 22470: ps 22470 Show detailed information about process with pid 22470: ps u 22470 -e, ax : list all processes. x : list processes of current user. -C cmdlist : select by command name. -u userlist, U userlist : select by effective user ID (EUID) or name. -f : full-format listing. -F : extra full format. -o, o : user-defined format. u : display user-oriented format. -w, w : wide output. Use this option twice for unlimited width. pstree - display a tree of processes. pidof - find the process ID of a running program. Show working directory of a process with pid 8367: pwdx 8367 Find procceses which use the file: fuser -v file list files opened by processes: lsof List processes that opened a file: lsof file_path List opened files of a process with pid 22470: lsof -p 22470 ------------------------------------------------------------------------------------------------- Users Show users list: cut -d: -f1 < /etc/passwd Print user identity: id Add user: useradd user_name Add user in Debian: adduser user_name Add user and specify his home directory: useradd -d directory_path user_name Add user and specify his home directory in Debian: adduser --home directory_path user_name Delete user: userdel user_name Delete user with his home directory: userdel -r user_name Delete user in Debian: deluser user_name Delete user with his home directory in Debian: deluser --remove-home user_name Change user password: passwd user_name Change current user password: passwd Show password status: passwd -S user_name Generate quality controllable random passphrase: pwqgen Show groups list: cat /etc/group Show user groups: groups user_name Add user to group: gpasswd --add user_name group Add user to administrator group: gpasswd --add user_name wheel Delete user from group: gpasswd --delete user_name group Add group: groupadd group_name Delete group: groupdel group_name Run a command from other user: sudo -u user_name command Run a command from other user variant 2: su -c command user_name Run shell from other user: su - user_name users - print the names of users currently logged in to the current host. lastlog - reports the most recent login of all users or of a given user. Print the lastlog record of the specified user: lastlog -u user_name last - show a listing of last logged in users. Show 10 last logins (may be other numbrer): last -10 -------------------------------------------------------------------------------------------------- journalctl journalctl - query the systemd journal. Show messages about errors: journalctl -b -p err Show messages about warnings and errors: journalctl -b -p warning Show messages about notices, warnings and errors: journalctl -b -p notice May also help on service error: journalctl -xe journalctl --disk-usage -b : show log from last boot. -b -1 : show log of previous boot. -n, --lines= : show the most recent journal events and limit the number of events shown. -r : reverse output so that the newest entries are displayed first. -f : show only the most recent journal entries, and continuously print new entries as they are appended to the journal. -k : show only kernel messages. --no-pager : do not pipe output into a pager. -e, --pager-end : immediately jump to the end in the pager. -x, --catalog : add message explanations where available. -t, --identifier=SYSLOG_IDENTIFIER Show messages for the specified syslog identifier SYSLOG_IDENTIFIER. Sample: journalctl -t sshd -u, --unit=UNIT|PATTERN Show messages for the specified systemd unit UNIT (such as a service unit), or for any of the units matched by PATTERN. Samples: journalctl _SYSTEMD_UNIT=vncserver.service journalctl _PID=28097 -------------------------------------------------------------------------------------------------- rsync rsync - versatile, remote and local file copying tool. За замовчанням rsync не копіює файл якщо він вже існує в цільовій папці і має той самий розмір та час зміни. Копіювати файл з індикатором прогресу: rsync --progress -h source destination Для копіювання папки потрібна опція -r. При опції -v (не потрібна при --progress) rsync буде пояснювати що він робить. При копіюванні папки за замовчанням в destination створюється одноімена папка і файли копіюються в неї. Щоб скопіювати файли з папки source в папку destination безпосередньо, потрібно після source вказати слеш. -h показувати числа в зручному для людини стилі. --list-only list the files instead of copying them : показати список файлів замість копіювання. -c, --checksum skip based on checksum, not mod-time & size : пропуск буде оснований на контрольній сумі а не на часі зміни і розміру. --size-only skip files that match in size : пропускати копіювання якщо оригінал та цільовий файл має однаковий розмір. -I, --ignore-times don't skip files that match size and time : не пропускати копіювання файлів. --delete delete extraneous files from dest dirs : видалити стороні файли з цільової папки. -z, --compress compress file data during the transfer. --stats показати підсумкову статистику після завершення. --exclude=PATTERN exclude files matching PATTERN. PATTERN задається відносно source. Якщо напочатку PATTERN є /, цей символ вважається початком відносного шляху. Замість шаблону можна вказати імя або відносний щлях файлу чи папки. Після папки потрібно вказати /. -r, --recursive recurse into directories. -l, --links copy symlinks as symlinks. -t, --times preserve modification times : зберігати час зміни файлів. -p, --perms preserve permissions. -o, --owner preserve owner (super-user only). -g, --group preserve group. ------------------------------------------------------------------------------------------------- systemctl and systemd systemctl - Control the systemd system and service manager. -a, --all When listing units with list-units, also show inactive units and units which are following other units. When showing unit/job/manager properties, show all properties regardless whether they are set or not. -n, --lines= When used with status, controls the number of journal lines to show, counting from the most recent ones. Takes a positive integer argument. Defaults to 10. --no-pager Do not pipe output into a pager. List running units: systemctl systemctl --type=service Show failed units: systemctl --failed Show service status: systemctl status service_name Help about unit: systemctl help unit_name Kill all service processes: systemctl kill service_name Start service: systemctl start service_name Stop service: systemctl stop service_name Enable service autostart: systemctl enable service_name Disable service autostart: systemctl disable service_name Block service start: systemctl mask service_name Unblock service start: systemctl unmask service_name A service file may be created in /etc/systemd/system directory. Analyze startup time: systemd-analyze Analyze services startup time: systemd-analyze blame Get default mode: systemctl get-default Set text mode (runlevel 3) as default: systemctl set-default multi-user.target Set graphical mode (runlevel 5) as default: systemctl set-default graphical.target -------------------------------------------------------------------------------------------------- grub Переустановити grub, якшо в системі є розділ boot, можна таким способом: 1) Завантажити лінукс з компакт диску або флешки. 2) Відкрити термінал і увійти в сеанс root командою su - 3) Змонтувати розділ boot в якусь папку. Якщо розділ boot це /dev/sda1 то змонтувати його в точку монтування /mnt/sda1 можна наприклад командами mkdir /mnt/sda1 mount /dev/sda1 /mnt/sda1 Додаткові опції до mount не обовязкові. Тип файлової системи визначиться автоматично. 4) Виконати команду grub2-install --boot-directory=точка_монтування_розділу_boot /dev/sda /dev/sda це завантажувальний пристрій. Замість /dev/sda може бути інший пристрій. Якщо --boot-directory не вказати, буде використовуватись папка /boot. Приклад: grub2-install --boot-directory=/mnt/sda1 /dev/sda 5) Переналаштувати grub командою grub2-mkconfig -o точка_монтування_розділу_boot/grub2/grub.cfg Приклад: grub2-mkconfig -o /mnt/sda1/grub2/grub.cfg 6) Перезавантажити компютер. Вибрати правильний варіант завантаження. Правильний варіант може бути наприклад Fedora (on /dev/sda2). /dev/sda2 це розділ для прикладу куди була встановлена Fedora, її кореневий розділ. 7) Після успішного завантаження переналаштувати grub командою sudo grub2-mkconfig -o /boot/grub2/grub.cfg ---------------------------------------------- Якщо в системі немає розділу boot, переустановити grub можна таким способом: 1) Завантажити лінукс з компакт диску або флешки. 2) Відкрити термінал і увійти в сеанс root командою su - 3) Змонтувати кореневий розділ в якусь папку. 4) Виконати команду grub2-install --boot-directory=точка_монтування_кореневого_розділу/boot /dev/sda /dev/sda це завантажувальний пристрій. Замість /dev/sda може бути інший пристрій. Приклад 1: grub2-install --boot-directory=/mnt/sda1/boot /dev/sda Приклад 2: grub2-install --boot-directory=/run/media/liveuser/root/boot /dev/sdb 5) Переналаштувати grub командою grub2-mkconfig -o точка_монтування_кореневого_розділу/boot/grub2/grub.cfg Приклад 1: grub2-mkconfig -o /mnt/sda1/boot/grub2/grub.cfg Приклад 2: grub2-mkconfig -o /run/media/liveuser/root/boot/grub2/grub.cfg Виконати пункти 6 та 7 з попереднього розділу. ---------------------------------------------- Переналаштувати grub: grub2-mkconfig -o /boot/grub2/grub.cfg Документація про grub: info grub2 Файл /etc/default/grub визначає те як grub буде налаштовуватись. Приклад файлу /etc/default/grub: GRUB_TIMEOUT=2 GRUB_DISABLE_SUBMENU=true GRUB_TERMINAL_OUTPUT="console" GRUB_CMDLINE_LINUX="rhgb quiet" GRUB_DISABLE_OS_PROBER=true GRUB_DISABLE_RECOVERY=true -------------------------------------------------------------------------------------------------- SELinux chcon - change file SELinux security context. Show SELinux alerts: sudo sealert -a /var/log/audit/audit.log Clear SELinux log: echo -n "" > /var/log/audit/audit.log Show policies list: semodule --list=full Remove policy: semodule -r policy_name Relabel file system: touch /.autorelabel; reboot -------------------------------------------------------------------------------------------------- Devices Show data about computer: sudo lshw | less Show short data about computer: sudo lshw -short Save data about computer in html file: sudo lshw -html > file_name Show data about motherboard and other devices: sudo lshw -class bus Show data about videocard: sudo lshw -class display sudo lshw -class processor Show data about operational memory: free -m free -h Show /dev/sda partitions list: sudo parted /dev/sda print Show /dev/sda partitions list with free space: sudo parted /dev/sda print free Check webcam: mplayer tv:// -tv driver=v4l2:width=640:height=480:device=/dev/video0:fps=30 mplayer tv:// device=/dev/video0 Monitor devices connecting and disconnecting: udevadm monitor Monitor devices connecting and disconnecting, show properties: udevadm monitor -p Show device info: udevadm info device_file udevadm info -a device_file sudo fdisk -l [device] List the partition tables for the specified devices and then exit. If no devices are given, those mentioned in /proc/partitions (if that file exists) are used. Display a list of mounted file systems: findmnt Get partition label, UUID and file system type: sudo blkid [device] If no device are given, all partitions will be shown. lsblk [options] [device ...] List information about block devices. lsblk -f List storage devices, their fs types, labels, UUIDs, mount points. lsblk -f -o +SIZE List storage devices, their fs types, labels, UUIDs, mount points, sizes. lsblk -o +FSUSED,LABEL List storage devices, include their used sizes and labels. lsblk -o NAME,TYPE,SIZE,FSUSED,LABEL,MOUNTPOINT Sample of storage devices list. Show information about SSD: smartctl -i device smartctl -a device Show SSD SMART attributes: smartctl -A device Show information about disks: lshw -class disk hwinfo --disk dmidecode - DMI table decoder. An information about motherboard, processor and other devices may be get by dmidecode. lscpu - display information about the processor. lsmem - list the ranges of available memory with their online status. lspci - list PCI devices. An information about videocard may be get by lspci. List USB devices: lsusb Build the nvidia kernel module: sudo akmods Set sound card profile: pactl set-card-profile card profile List sound cards: pactl list cards pactl list short cards pactl list sinks pactl list short sinks aplay -l List PCMs: aplay -L Play file: aplay file_name Play file to specified PCM: aplay -D PCM_name file_name List power sources: upower -e Show power source state: upower -i power_source_path Detect sensors: sudo sensors-detect sensors - print sensors information. Monitor sensors: watch -t sensors -A Show kernel parameters: cat /proc/cmdline List input devices: xinput --list List input device properties: xinput --list-props device_id_or_name Slow doun mouse: xinput --set-prop device_id_or_name 'Coordinate Transformation Matrix' 0.7 0 0 0 0.7 0 0 0 1 List available bluetooth adapters: bt-adapter -l Show information about bluetooth adapter: bt-adapter -i Discover remote bluetooth devices: bt-adapter -d List bluetooth devices: bt-device -l Show information about bluetooth device: bt-device -i Connect to the bluetooth device and initiate the pairing: bt-device -c Disconnect bluetooth device: bt-device -d Remove bluetooth device: bt-device -r Control bluetooth device: bluetoothctl ----------------------------------------------------------------------------------- bluetoothctl commands List available controllers: list Controller information: show [controler] Scan for devices: scan on List available devices: devices List paired devices: paired-devices Device information: info Remove device: remove Disconnect device: disconnect [device] Connect device: trust pair connect -------------------------------------------------------------------------------------------------- Kernel modules List kernel modules: find /lib/modules/$(uname -r) -name '*.ko*' List loaded kernel modules: lsmod Show module info: modinfo module_name Load module: modprobe module_name Load module from file: insmod file_name [args] Unload module: modprobe -r module_name Unload module, alternative variant: rmmod module_name Loaded modules may be found in /sys/module. Modules marameters values may be found in /sys/module/module_name/parameters. -------------------------------------------------------------------------------------------------- Important grep options Regexp selection and interpretation: -E, --extended-regexp PATTERN is an extended regular expression -F, --fixed-strings PATTERN is a set of newline-separated strings -i, --ignore-case ignore case distinctions -w, --word-regexp force PATTERN to match only whole words -x, --line-regexp force PATTERN to match only whole lines -v, --invert-match select non-matching lines Output control: -m, --max-count=NUM stop after NUM matches -b, --byte-offset print the byte offset with output lines -n, --line-number print line number with output lines -H, --with-filename print the file name for each match -h, --no-filename suppress the file name prefix on output -o, --only-matching show only the part of a line matching PATTERN -q, --quiet, --silent suppress all normal output -d, --directories=ACTION how to handle directories; ACTION is 'read', 'recurse', or 'skip' -r, --recursive like --directories=recurse -R, --dereference-recursive likewise, but follow all symlinks --include=FILE_PATTERN search only files that match FILE_PATTERN --exclude=FILE_PATTERN skip files and directories matching FILE_PATTERN --exclude-dir=PATTERN directories that match PATTERN will be skipped. -L, --files-without-match print only names of FILEs containing no match -l, --files-with-matches print only names of FILEs containing matches -c, --count print only a count of matching lines per FILE Context control: -B, --before-context=NUM print NUM lines of leading context -A, --after-context=NUM print NUM lines of trailing context -C, --context=NUM print NUM lines of output context -NUM same as --context=NUM --group-separator=SEP use SEP as a group separator --no-group-separator use empty string as a group separator ------------------------------------------------------------------------------- git commands git apply ctools-1444006-disallowed-unicode-code-point-18.patch git config --global user.name 'Sergiy Vovk' git config --global user.email grayvovk@meta.ua git config --list git init git add testscript.php git add . Commit: git commit -m 'Message.' Change message of last commit: git commit --amend -m 'Message.' Restore testscript.php from last commit: git checkout -- testscript.php git log git log --pretty=oneline git clone git://github.com/schacon/grit.git git remote add pb git://github.com/paulboone/ticgit.git git remote rm pb git remote git remote -v git fetch pb git pull git push git push origin master git tag - tags list. git tag v1.4 - add v1.4 tag to the last commit. git tag -a v1.4 -m 'version 1.4' git show v1.4 - show v1.4 tag data. git branch testing - create testing branch. git checkout testing - select testing branch. git checkout -b testing - create testing branch and select it. git branch -d testing - delete testing branch. git branch - branches list. git branch -v - branches and last commits list. git branch --merged - list merged branches. git merge testing - merge testing branch to current branch. View remote url: git remote -v Change the origin remote url: git remote set-url origin https://github.com/user/repo.git ------------------------------------------------------------------------------------------ ip ip - show / manipulate routing, network devices, interfaces and tunnels Network device configuration: ip link [command] List network interfaces: ip link List up network interfaces: ip link show up Show network interfaces statistic: ip -s -h link Show wlp3s0 interface statistic: ip -s -h link show wlp3s0 Show wlp3s0 interface attributes: ip link show wlp3s0 Set enp2s0 interface up: sudo ip link set enp2s0 up Set enp2s0 interface down: sudo ip link set enp2s0 down ------------------------------------------------------------------------------------------ nmcli and PPPoE nmcli - command-line tool for controlling NetworkManager. Show status for all network devices: nmcli device Show information about all network devices: nmcli device show Show information about wlp3s0 network device: nmcli device show wlp3s0 Show wifi access points status: nmcli device wifi Connect to wifi access point MyHomeNet: nmcli device wifi connect MyHomeNet Connect to wifi access point MyHomeNet with password prompt: nmcli --ask device wifi connect MyHomeNet List network connection: mcli connection Show MyHomeNet connection information: mcli connection show MyHomeNet Встановити пакунки для PPPoE: sudo dnf -y install ppp rp-pppoe net-tools initscripts Налаштувати PPPoE: sudo pppoe-setup Підняти підключення PPPoE: sudo ifup ppp0 ------------------------------------------------------------------------------------------- Work with MySQL database Change MySQL password for root user: mysqladmin -u root password 365abc mysql -u vovk -p369 shop Show databases list: mysqlshow -u root -p Show tables list: mysqlshow -u user_name -p database_name Команда для імпорту файлу sql в базу даних: mysql -u user_name -p database_name < sql_file_name Команда для імпорту файлу gz в базу даних: gunzip -c gz_file_name|mysql -u user_name -p database_name Команда для експорту бази даних в файл: mysqldump -u user_name -p database_name > sql_file_name -h host_name : connect to the MySQL server on the given host. -------------------------------------------------------------------------------- Запустити qmmp о 21:00 сьогодні: echo 'DISPLAY=:0 qmmp' | at 21:00 today Запустити qmmp о 21:00 завтра: echo 'DISPLAY=:0 qmmp' | at 21:00 tomorrow Запустити qmmp через 5 хвилин: echo 'DISPLAY=:0 qmmp' | at now + 5 minutes Запустити qmmp через 5 годин: echo 'DISPLAY=:0 qmmp' | at now + 5 hours Вивести список призначених завдань: atq Вивести команду для призначеного завдання: at -c номер Видалити призначене завдання: atrm номер DISPLAY=:0 потрібна для графічної програми. -------------------------------------------------------------------------------- The cron fields: field allowed values ----- -------------- minute 0-59 hour 0-23 day of month 1-31 month 1-12 (or names) day of week 0-7 (0 or 7 is Sun, or use names) command Task install example: echo '0 12 * * 2,4 /home/taras/Scripts/UpdateApartmentDatabase.sh' | crontab - Note: the old tasks will be removed. Run /root/vsystemchecker every 30 minute: */30 * * * * /root/vsystemchecker > /var/log/vsystemchecker.log List tasks of current user: crontab -l List tasks of taras user: crontab -u taras -l Edit tasks: crontab -e Remove task: crontab -r -------------------------------------------------------------- dnf and rpm commands Get upgrades list for installed packages: dnf list upgrades List packages from repo: dnf repository-packages repo_name list --all List orphaned packages: rpmorphan --all List unused packages: dnf list autoremove Remove unused packages: dnf autoremove Add repo file to dnf configuration: dnf config-manager --add-repo repo_file The repo_file may be also in internet. Get installed packages list: rpm -qa | sort rpm -qa --queryformat '%{NAME}\n' | sort rpm -qa --queryformat '%{NAME}: %{SUMMARY}\n' | sort Get package files list: dnf repoquery -l package_name rpm -ql package_name rpm -qlp package_file Get package information: rpm -qi package_name rpm -qip package_file Get package name of file: dnf provide patern dnf repoquery --file file rpm -qf file Verify package: rpm -V package_name Install package: rpm -ihv package_file -------------------------------------------------------------- btrfs commands Format partition to btrfs file system: sudo mkfs.btrfs -L label -f device Check btrfs file system: sudo btrfs check device Check btrfs file system, verify data checksums: sudo btrfs check --check-data-csum -p device -p: show progress. Check data integrity on btrfs filesystem, repair danaged data if posible: sudo btrfs scrub start -B device_or_path Other way: sudo btrfs scrub start device_or_path sudo btrfs scrub status device_or_path Repair btrfs file system: sudo btrfs check --repair device Show information about filesystem usage: btrfs filesystem usage partition-mount-point Show short information about filesystem: btrfs filesystem df partition-mount-point Show information about filesystem: sudo btrfs filesystem show device If device is not specified, information about all btrfs filesystems is shown. Show label: btrfs filesystem label device-or-mountpoint Set label: sudo btrfs filesystem label device-or-mountpoint new-label Defragment filesystem: sudo btrfs filesystem defragment -v -r directory If the filesystem has more than 1 subvolumes, each subvolume should be defragmented separately. Save subvolume to file: sudo btrfs send -f file subvolume-path Restore subvolume from file: sudo btrfs receive -f file partition-mount-point List subvolumes: sudo btrfs subvolume list partition-mount-point Create subvolume: sudo btrfs subvolume create partition-mount-point/subvolume-name Create subvolume snapshot: sudo btrfs subvolume snapshot subvolume-path snapshot-path Create subvolume readonly snapshot: sudo btrfs subvolume snapshot -r subvolume-path snapshot-path A subvolume may be copied by btrfs subvolume snapshot command. A usual subvolume may be created from readonly subvolume by btrfs subvolume snapshot command. Delete subvolume: sudo btrfs subvolume delete partition-mount-point/subvolume-name Rename subvolume: sudo mv path new-path Show information about subvolume: sudo btrfs subvolume show partition-mount-point/subvolume-name -------------------------------------------------------------- snap commands List installed snaps: snap list Find snap: snap find text Get snap info: snap info snap_name Run snap: snap run snap_name Install snap: sudo snap install snap_name Remove snap: sudo snap remove snap_name Update snap: sudo snap refresh snap_name Update all snaps: sudo snap refresh -------------------------------------------------------------- CentOS commands Enable auto load of httpd service: chkconfig httpd on chkconfig --level 2 httpd off Disable auto load of httpd service: chkconfig httpd off Show auto load status of httpd service: chkconfig --list httpd Show auto load status of all services: chkconfig --list -------------------------------------------------------------- Ubuntu and Debiam commands service - run a System V init script Sample: service vsftpd status List services and its statuses: service --status-all initctl list - services list. Reload nginx server: service nginx reload Restart ssh server: service ssh restart Update packages database: apt update Update all packages in Ubuntu: apt upgrade Update all packages in Debian: aptitude safe-upgrade List packages: apt list [pattern] Show information about package: apt show package_name Find package: aptitude search string Find package by file name: dpkg -S file_name List packages matching given pattern: dpkg -l package-name-pattern Report status of specified package: dpkg -s package-name List package files: dpkg -L package_name Install package from file: dpkg -i file_name install missing dependicies: apt-get -f install Install or update package: apt install package_name Reinstall package: apt install --reinstall package_name Remove package: apt remove package_name Show holded packages list: dpkg --get-selections | grep hold Disable package update: echo 'package_name hold' | dpkg --set-selections Enable package update: echo 'package_name install' | dpkg --set-selections Find package by file path: apt-file search file_path