Linux cheat sheet что это

Оболочка Bash — шпаргалка для начинающих

В данной шпаргалке затрагиваются следующие темы: введение в оболочку, навигация, основные команды, переменные окружения, коннекторы, конвейеры, перенаправление ввода/вывода, права доступа и комбинации клавиш.

Оболочка Bash: введение

Оболочка, или шелл (shell) — это программа, в нашем случае названная «bash», что является сокращением от Bourne Again Shell. Оболочка принимает ваши команды и передаёт их операционной системе. Для взаимодействия с системой используются терминалы, такие как gnome-terminal, eterm, nxterm и т. п.

В Linux файлы и каталоги имеют иерархическую организацию, то есть существует некий начальный каталог, называемый корневым. В нём содержатся файлы и подкаталоги, которые в свою очереди содержат файлы и свои подкаталоги.

Команда pwd , сокращение от print working directory, отображает текущее местоположение в структуре каталогов.

Команда cd позволяет перейти в новый каталог.

Синтаксис Объяснение
cd Перемещение в домашний каталог
cd

Перемещение в домашний каталог
cd .. Перемещение на один уровень выше
cd — Перемещение в предыдущий каталог
cd Directory1 Перемещение в каталог Directory1
cd Directory1/Directory2 Перемещение в каталог Directory2 по указанному пути

mkdir

Команда mkdir создаёт новый каталог в текущем каталоге.

Основные команды

Команда man отображает руководства по командам. Например, следующая команда выдаст всю информацию о команде cat :

Команда cat считывает файл, переданный как аргумент, и выводит его содержимое по стандартному каналу вывода. Передача нескольких файлов в виде аргумента приведёт к выводу конкатенированного содержимого всех файлов.

Команда echo выводит свои аргументы по стандартному каналу вывода.

Если вызвать echo без аргументов, будет выведена пустая строка.

Команда head читает первые 10 строк любого переданного текста и выводит их по стандартному каналу. Число выводимых строк можно изменить:

Команда tail работает аналогично команде head , но читает строки с конца:

Также можно просматривать добавляемые к файлу строки в режиме реального времени при помощи флага -f :

Команда less позволяет перемещаться по переданному файлу или куску текста, причём в обоих направлениях.

Подробнее о назначении символа | будет рассказано ниже в разделе команды history .

Обычные сочетания клавиш Описание
G Перемещает в конец файла
g Перемещает в начало файла
:50 Перемещает на 50 строку файла
q Выход из less
/searchterm Поиск строки, совпадающей с ‘searchterm’, ниже текущей строки
/ Перемещает на следующий подходящий результат поиска
?searchterm Поиск строки, совпадающей с ‘searchterm’, выше текущей строки
? Перемещает на следующий подходящий результат поиска
up Перемещает на одну строку выше
down Перемещает на одну строку ниже
pageup Перемещает на одну страницу выше
pagedown Перемещает на одну страницу ниже

Команда true всегда возвращает ноль в качестве выходного статуса для индикации успеха.

false

Команда false всегда возвращает не-ноль в качестве выходного статуса для индикации неудачи.

$? — это переменная, которая содержит выходной статус последней запущенной команды. Под статусом обычно понимается код возврата программы. 0 означает успешное выполнение программы, любое значение большее 0 отражает тот факт, что в процессе выполнения возникли некоторые ошибки. Кстати, именно поэтому в bash истинной (true) считается 0, а все, что не 0 — ложью (false):

Команда grep занимается поиском переданной строки в указанном файле:

grep также может принимать несколько файлов и регулярных выражений для уточнения формата текста.

Обычные флаги Описание
-i Отключение чувствительности к регистру
-r Рекурсивный поиск по директориям
-w Поиск только целых слов
-c Вывод количества найденных элементов
-n Вывод всей строки, содержащей запрос
-v Вывод инвертированного совпадения

Также можно ознакомиться с руководством по regex. У нас на сайте тоже есть руководство по «регуляркам» в Python для новичков.

Команда sed — это потоковый редактор, преобразующий входные текстовые данные. Обычно её используют для замены выражений так: s/regexp/replacement/g . Например, следующий код заменит все слова «Hello» на «Hi»:

Также вы можете ознакомиться с руководством по sed.

history

Команда history выводит историю командной строки. Обычно её используют вместе с командой grep для поиска конкретной команды. Например, следующий код найдёт все команды, содержащие строку g++ :

Здесь также используется символ | — это так называемый конвейер (pipe). Благодаря ему можно перенаправлять вывод одной команды на вход другой — таким образом в примере выше вся история, которая в обычном режиме выводится командой history прямо в вывод терминала, будет перенаправлена в grep в качестве входных данных. Мы не увидим вывода команды history , но увидим вывод команды grep .

Это может быть довольно сложно для понимания без практики, поэтому поэкспериментируйте самостоятельно, например с командами ls , history , ps (описана ниже), перенаправляя их вывод в grep , sed или less , например.

export

Команда export устанавливает переменные окружения для передачи дочерним процессам. Например, так можно передать переменную name со значением student :

Команда ps выводит информацию о запущенных процессах.

Выводится четыре элемента:

  • ID процесса (PID),
  • тип терминала (TTY),
  • время работы процесса (TIME),
  • имя команды, запустившей процесс (CMD).

Команда awk находит и заменяет текст в файлах по заданному шаблону: awk ‘pattern ‘ test.txt

Команда wget скачивает файлы из Сети и помещает их в текущий каталог.

Команда nc — это утилита для отладки сети. Также можно ознакомиться с руководством по nc.

Команда ping тестирует сетевое подключение.

Статистика в конце показывает количество подключений, совершённых до завершения команды, и время их выполнения.

Git — это популярная система контроля версий. Также можно ознакомиться с руководством по git и нашими материалами.

Переменные окружения

Переменные окружения — это именованные переменные, содержащие значения, используемые одним или несколькими приложениями.

Переменная PATH содержит список каталогов, в которых система ищет исполняемые файлы.

11–13 октября, Онлайн, Беcплатно

Переменная HOME содержит путь к домашнему каталогу текущего пользователя.

Коннекторы

Коннекторы позволяют запускать несколько команд одновременно.

Коннектор Описание
&& Первая команда исполняется всегда, вторая — только в случае успешного завершения первой
|| Первая команда исполняется всегда, вторая — только в случае неудачного завершения первой
; Команды исполняются всегда

Конвейеры

Конвейеры, или пайпы, позволяют соединять входные и выходные каналы различных команд. В следующем примере вывод команды ls будет передан в head , и в результате будет напечатано лишь 10 первых элементов.

Перенаправление ввода/вывода

Перенаправление вывода

Для стандартного перенаправления вывода используются символы > и >> .

Например, этот код передаст вывод ls в файл, а не на экран:

Если файл не существует, он создаётся, а если существует, то перезаписывается. Во избежание перезаписи стоит использовать команду >> — она дописывает данные в конец файла.

Перенаправление ввода

Для стандартного перенаправления вывода используется символ . В следующем примере sort берет входные данные из файла, а не с клавиатуры:

Команда sort выводит содержимое файла на экран, поскольку мы не перенаправили выход. Это можно сделать так:

Продвинутое перенаправление

Добавление & к > приводит к перенаправлению как стандартного потока выхода, так и потока ошибок. Например, файл test.cpp выведет строку stdout в cout и строку stderr в cerr .

Если вы хотите вывести конкретный файловый дескриптор, вы можете приписать его номер к > .

Имя Дескриптор Описание
stdin 0 Стандартный поток ввода
stdout 1 Стандартный поток вывода
stderr 2 Стандартный поток вывода ошибок

Например, для перенаправления stderr в test.txt нужно сделать следующее:

Права доступа

Команда ls -l выводит много информации о правах доступа к каждому файлу:

Вывод в примере Описание / возможные выводы
Тип файла:
— файл
d каталог
rw- Права доступа владельца файла
rw- Права доступа членов группы-владельца файла
r– Права доступа прочих пользователей
user Имя владельца файла
group Имя группы-владельца файла

chmod

Команда chmod изменяет права доступа файла. Вот типичные сочетания флагов для изменения прав конкретных пользователей:

Буква Пользователь
u Владелец
g Член группы
o Прочие пользователи
a Все пользователи

Вы можете вызвать chmod с описанием действий над конкретным файлом. Символ — обозначает удаление прав, символ + — добавление. Следующий пример сделает файл доступным для чтения и записи владельцу и группе:

Кроме того, chmod можно использовать с восьмеричными числами, где 1 — это наличие прав, а 0 — отсутствие:

Следующая команда сработает так же, как и предыдущая:

Сочетания клавиш

Сочетание Описание
CTRL-A Перемещение курсора в начало строки
CTRL-E Перемещение курсора в конец строки
CTRL-R Поиск по истории
CTRL-W Вырезать последнее слово
CTRL-U Вырезать всё до курсора
CTRL-K Вырезать всё после курсора
CTRL-Y Вернуть последнюю вырезанную строку
CTRL-_ Отмена
CTRL-L Очистка экрана терминала

Хинт для программистов: если зарегистрируетесь на соревнования Huawei Cup, то бесплатно получите доступ к онлайн-школе для участников. Можно прокачаться по разным навыкам и выиграть призы в самом соревновании.

Перейти к регистрации

Источник

100+ Linux commands cheat sheet & examples

Table of Contents

In this cheat sheet tutorial I have consolidated a list of Linux commands with examples and man page link to give you an overview on Linux day to day usage. We know Linux is one of the preferred choice for most of the IT domains so having basic knowledge of Linux is mandatory for everyone. I have divided the Linux commands into different section so you can choose to only concentrate on the commands which suits your domain.

I will keep adding and updating this article from time to time to add more commands.

Environment Variables

Variables are local, which means they are specific to a process. Local means local to a process. For example, when you log in on a terminal or open a terminal emulator, you start a process that runs a shell and create this variable TEST with value as deepak

Verify the content of this variable

Now you open another terminal of the same Linux server and try to access this variable,

The output would be empty, so our variable is only accessible in the terminal where we created.

Command Example/Syntax Comments For more details
printenv # printenv

# printenv PATH Displays environment variable names and values.
When called with the name of an environment variable, it displays the value of that variable. man page for printenv env # env The env utility runs a program as a child of the current shell, allowing you to modify the environment the current shell exports to the newly created process. man page for env export # export TEST=deepak
# env | grep TEST

TEST=deepak When you run an export command with variable names as arguments, the shell places the names (and values, if present) of those variables in the environment. man page for export set # TEST=deepak
# set | grep TEST

TEST=deepak Display variables in the current shell
These variables comprise shell variables (variables not in the environment) and environment variables. man page for set

File Management

The commands under this section are very basic commands and must be known to every system administrator. This is definitely not the complete list of Linux commands for file management but can give you a kickstart and can cover most of the basic to complex scenarios.

Command Example/Syntax Comments For more details
ls # ls List files man page for ls
# ls -l Long list files
# ls -la Long list files including hidden files
# ls -ltr Long list files and sort by modification time. oldest placed first.
cat # cat FILENAME Print the content of the provided file on the terminal man page for cat
less # less FILENAME When you want to view a file that is longer than one screen, you can use either the less utility or the more utility.
It will pause after displaying a screen of text
You can use keyboard arrow to navigate around the file to read the text
Press q to return to the shell
man page for less
more # more FILENAME more command is also similar to less but has few restrictions
We cannot use navigation arrow from the keyboard while reading with more
You must use SPACE bar to scroll through the file
Press q to return to console
man page for more
head # head -n 5 FILENAME This example displays the top 5 lines of provided file
By default the head utility displays the first ten lines of a file.
man page for head
tail # tail -n 5 FILENAME This example will display the last 5 lines of the provided file
By default tail will show the last 10 lines of the file
man page for tail
# tail -f /var/log/messages To continuously monitor the incoming log messages into /var/log/messages file in runtime
sort # sort FILENAME Displays a File in Order
The sort utility displays the contents of a file in order by lines
It does not change the original file.
The –u option generates a sorted list in which each line is unique (no duplicates).
The –n option puts a list of numbers in numerical order.
man page for sort
uniq # uniq FILENAME The uniq (unique) utility displays a file, skipping adjacent duplicate lines; it does not change the original file.
If a file contains a list of names and has two successive entries for the same person, uniq skips the extra line
man page for uniq
file # file FILENAME Identifies the Contents of a File
You can use the file utility to learn about the contents of any file on a Linux system without having to open and examine the file yourself.
man page for file
# file dataFile.txt
dataFile.txt: ASCII text
file command identified the dataFile.txt type as ASCII text
cp # cp SOURCE-FILE DESTINATION-FILE The cp (copy) utility makes a copy of a file.
The SOURCE-FILE is the name of the file that cp will copy.
The DESTINATION-FILE is the name cp assigns to the resulting (new) copy of the file.
If the DESTINATION-FILE exists before you give a cp command, cp overwrites it.
man page for cp
# cp /root/myfile /tmp/dir1/ This command copied myfile from /root to /tmp/dir1 directory
mv # mv EXISTING-FILENAME NEW-FILENAME Changes the Name of a File
The mv (move) utility can rename a file without making a copy of it. The mv command line specifies an existing file and a new filename using the same syntax as cp
man page for mv
# mv /root/debug.log /tmp/new_debug.log In this example we rename the name of debug.log file to new_debug.log and also changed the location of the file from /root/ to /tmp
grep # grep STRING FILENAME The grep utility searches through one or more files to see whether any contain a specified string of characters.
This utility does not change the file it searches but simply displays each line that contains the string.
man page for grep
# grep ssh /etc/services In this example we search for all the lines containing «ssh» in /etc/services file
mkdir # mkdir DIR Create directories man page for mkdir
touch # touch FILE Create empty file man page for touch
pwd # pwd present working directory man page for pwd

Finding files and directories

Most of the time we will end up using find command to find files and directories. But I also like which command as it gives is the path of the binary which is required at multiple events when we are required to execute a binary with complete PATH.

Command Example/Syntax Comments For more details
which # which PROGRAMNAME which will print the full path of the provided PROGRAMNAME on STDOUT
It does this by searching for an executable or script in the directories listed in the environment variable PATH .
man page for which
# which useradd
/usr/sbin/useradd
In this example we are searching for the path of useradd command
whereis # whereis FILENAME whereis attempts to locate the desired program in the standard Linux places, and in the places specified by $PATH and $MANPATH man page for whereis
# whereis sshd
sshd: /usr/sbin/sshd /usr/share/man/man8/sshd.8.gz
In this example we are searching for the path of sshd binary and the man page location for sshd file
locate # locate FILENAME The locate utility ( locate package; some distributions use mlocate ) searches for files on the local system:
Before you can use locate ( mlocate ), the updatedb utility must build or update the locate ( mlocate ) database. Typically the database is updated once a day by a cron script
man page for locate
# locate sshd
/etc/pam.d/sshd
/etc/ssh/sshd_config
/etc/sysconfig/sshd
In this example we are searching for all files in your Linux server containing string sshd in their name
find # find PATH OPTIONS FILENAME find command will search for file or directory based on the OPTIONS provided find cmnd examples
# find / -type f -name sshd In this example we are searching for a file named sshd inside / location

Check User Information

These are some of the commands which we use to check the last logged in user information and some other commands to get more details on existing user.

Command Example/Syntax Comments For more details
who # who -u The who utility displays a list of users who are logged in on the local system. man page for who
users # users Print the user names of users currently logged in to the current host
It does not give much information apart from usernames
man page for users
last # last -a This command searches back through the file /var/log/wtmp (or the file designated by the -f flag) and displays a list of all users logged in (and out) since that file was created. man page for last
finger # finger If no arguments are specified, finger will print an entry for each user currently logged into the system. man page for finger
whoami # whoami Print the user name associated with the current effective user ID man page of whoami
id # id Print real and effective user and group IDs man page for id
w # w The first line the w utility displays is the same as the output of uptime command. Following that line, w displays a list of the users who are logged in.

Check System Information

As a sytem and Linux administrator you must be familiar with these commands. These will help you determine the type of server you are working on, such as load, cpu model, hardware model, hardware type etc. Some of the commands may be distribution specific such as hwinfo is only available in SuSE Linux while others are expected to be found on almost all distros.

Command Example/Syntax Comments For more details
uptime # uptime The uptime utility displays a single line that includes the time of day, the period of time the computer has been running (in days, hours, and minutes), the number of users logged in, and the load average (how busy the system is). The three load average numbers represent the number of jobs waiting to run, averaged over the past 1, 5, and 15 minutes. man page for uptime
free # free -m The free utility displays the amount of physical (RAM) and swap memory in the local system. It displays columns for total, used, and free memory as well as for kernel buffers. Linux Memory Management
dmidecode # dmidecode -t system dmidecode is a tool for dumping a computer’s DMI (some say SMBIOS) table contents in a human-readable format. This table contains a description of the system’s hardware components, as well as other useful pieces of information such as serial numbers and BIOS revision man page for dmidecode
lshw # lshw lshw is a small tool to extract detailed information on the hardware configuration of the machine. It can report exact memory configuration, firmware version, mainboard configuration, CPU version and speed, cache configuration, bus speed, etc man page for lshw
hwinfo # hwinfo hwinfo is used to probe for the hardware present in the system. It can be used to generate a system overview log which can be later used for support. (available only with SuSE) man page for hwinfo
lscpu # lscpu lscpu gathers CPU architecture information from sysfs, /proc/cpuinfo and any applicable architecture-specific libraries (e.g. librtas on Powerpc). man page for lscpu
lspci # lspci lspci is a utility for displaying information about PCI buses in the system and devices connected to them. man page for lspci
/proc/cpuinfo # cat /proc/cpuinfo Provides information about the CPU model, architecture, processors, available modules, and many more CPU related information. lscpu gathers information from this file, man page for lscpu
uname # uname [OPTIONS] Print system information man page for uname

Manage System Processes

These Linux commands will help you manage the Linux processes, and will help you troubleshoot any server resource related issues. You can use these commands to monitor your server’s resource such as Memory, CPU, disk IO etc.

Command Example/Syntax Comments For more details
ps # ps [OPTIONS] ps displays information about a selection of the active processes. If you want a repetitive update of the selection and the displayed information, use top instead. man page for ps
nice # nice [OPTIONS] Run COMMAND with an adjusted niceness, which affects process scheduling. With no COMMAND, print the current niceness. Niceness values range from -20 (most favorable to the process) to 19 (least favorable to the process). nice example
renice # renice [OPTIONS] PID renice alters the scheduling priority of one or more running processes. The first argument is the priority value to be used. The other arguments are interpreted as process IDs (by default), process group IDs, user IDs, or user names. renice example
# renice -n 15 1121
1121 (process ID) old priority 0, new priority 15
In this example I have changed the nice value of PID 1121 from 0 to 15
top # top The top program provides a dynamic real-time view of a running system. It can display system summary information as well as a list of processes or threads currently being managed by the Linux kernel. top examples
pgrep # pgrep [OPTIONS] PATTERN pgrep looks through the currently running processes and lists the process IDs which match the selection criteria to stdout. man page for pgrep
pkill # pkill [OPTIONS] PATTERN pkill will send the specified signal (by default SIGTERM) to each process instead of listing them on stdout. man page for pkill
kill # kill [OPTIONS] PID The command kill sends the specified signal to the specified processes or process groups. man page for kill
sar # sar [OPTIONS] The sar command writes to standard output the contents of selected cumulative activity counters in the operating system. The accounting system, based on the values in the count and interval parameters, writes information the specified number of times spaced at the specified intervals in seconds. If the interval parameter is set to zero, the sar command displays the average statistics for the time since the system was started. sar examples
vmstat # vmstat [OPTIONS] vmstat reports information about processes, memory, paging, block IO, traps, disks and cpu activity. man page for vmstat
iostat # iostat [OPTIONS] The iostat command is used for monitoring system input/output device loading by observing the time the devices are active in relation to their average transfer rates. man page for iostat
crond # crond [OPTIONS] crond daemon is used to execute scheduled commands. You can create new job using crontab -e and provide the time when the script should be executed and the script path crond examples

Managing Users and Groups

These are some of the basic Linux commands to perform user management such as create, modify, delete user or groups.

Command Example/Syntax Comments For more details
useradd # useradd USERNAME The useradd command creates a new user account using the values specified on the command line plus the default values from the system. Depending on command line options, the useradd command will update system files and may also create the new user’s home directory and copy initial files. useradd examples
usermod # usermod OPTIONS USERNAME The usermod command modifies the system account files to reflect the changes that are specified on the command line. man page of usermod
# usermod -G admin deepak In this example I am adding additional group to my existing deepak user
userdel # userdel USERNAME The userdel command modifies the system account files, deleting all entries that refer to the user name USERNAME . The named user must exist man page for userdel
passwd # passwd USERNAME The passwd utility is used to update user’s authentication token(s).
You can lock, unlock, assign passwords using passwd utility for any system user
passwd examples
groupadd # groupadd GROUPNAME The groupadd command creates a new group account using the values specified on the command line plus the default values from the system. The new group will be entered into the system files as needed add or remove user from group
groupdel # groupdel GROUPNAME The groupdel command modifies the system account files, deleting all entries that refer to GROUPNAME . The named group must exist. add or remove user from group
groupmod # groupmod [options] GROUPNAME The groupmod command modifies the definition of the specified GROUP by modifying the appropriate entry in the group database. add or remove user from group
# groupmod -n administrator admin In this example I am renaming the group name from admin to administrator
sudo $ sudo OPTIONS COMMAND sudo allows a permitted user to execute a command as the superuser or another user, as specified by the security policy. Add sudo permisison
$ sudo systemctl network restart Observe the $ sign in the beginning of the shell, it donates a normal user shell. A root user’s shell will have hash ( # )
So in this example a normal user is performing network restart using sudo privilege

Managing Permissions

Linux permission is a very vast topic and here I have only covered the basic commands which we use to assign/modify/remove permissions to files and directories.

Command Example/Syntax Comments For more details
chown # chown OPTIONS USER:GROUP TARGET chown changes the user and/or group ownership of each given file or directory
USER represents the user owner of the target file
GROUP represents the group owner of the target file
TARGET represents any file or directory or PATH
man page for chown
# chown deepak:admin /tmp/file In this example I am assigning user owner permission to deepak , group owner permission to admin group for /tmp/file
chmod # chmod PERM PATH chmod changes the file mode bits i.e. PERM of each given file according to mode, which can be either a symbolic representation of changes to make, or an octal number representing the bit pattern for the new mode bits man page for chmod
# chmod 755 /tmp/dir1 In this example I am changing permission of /tmp/dir1 to 755 i.e. full permission for user, read+execute permission for group and other users
chgrp # chgrp GROUPNAME FILE Change group ownership of files and directories
GROUPNAME represents the group to be assigned for FILE
man page for chgrp
# chgrp admin /tmp/file In this example we are changing the group ownership to admin group for /tmp/file
groups # groups USERNAME Print group memberships for each USERNAME man page for groups
# groups deepak
deepak : deepak admin
In this example we are checking the list of group which user deepak is part of.
newgrp $ newgrp GROUPNAME The newgrp command is used to change the current group ID during a login session man page for newgrp
$ id
uid=1001(deepak) gid=1001(deepak) groups=1001(deepak),1003(admin)

$ newgrp admin

$ id
uid=1001(deepak) gid=1003(admin) groups=1003(admin),1001(deepak) In this example we are changing the primary group of user deepak to admin group setfacl # setfacl OPTIONS FILE This utility sets Access Control Lists (ACLs) of files and directories.
It is useful to give individual permission to users and groups as chmod assigns permission of file level but here we have more control over each user permission setfacl examples # setfacl -m u:deepak:rx /tmp/file In this example I am giving read and execute permission for user deepak for /tmp/file getfacl # getfacl FILE For each file, getfacl displays the file name, owner, the group, and the Access Control List (ACL). If a directory has a default ACL, getfacl also displays the default ACL getfacl examples # getfacl /tmp/file
getfacl: Removing leading ‘/’ from absolute path names
# file: tmp/file
# owner: root
# group: admin
user::rw-
user:deepak:r-x
group::r—
mask::r-x
other::r— In this example I am collecting the acl permission list from /tmp/file
It has the permission detail which we applied earlier with setfacl chattr # chattr OPTIONS FILE chattr changes the file attributes on a Linux file system chattr examples # chattr +i /tmp/file In this example we have restricted the modification permission on /tmp/file . Now not even root user can modify the content of /tmp/file
To remove this permission use chattr -i /tmp/file lsattr # lsattr FILE list file attributes on a Linux second extended file system. By default ls command will not show the permission attributes applied by chattr so we must use lsattr to get these details lsattr examples # lsattr /tmp/file
—-i———e—- /tmp/file In this example we can see the «i» attribute which we added with chattr in the previous example
The ‘e’ attribute indicates that the file is using extents for mapping the blocks on disk. It may not be removed using chattr

Configure and Troubleshoot Network

This section will help Network engineers who are new to Linux environment. I have tried to place the most used commands for network troubleshooting, we also have tcpdump, iperf, netperf and many other networking tools which are used for troubleshooting network related issues but they can get complicated hence those are not mentioned in this list.

Command Example/Syntax Comments For more details
ifconfig # ifconfig This program is obsolete! For replacement check ip addr and ip link . For statistics use ip -s link .
If no arguments are given, ifconfig displays the status of the currently active interfaces. If a single interface argument is given, it displays the status of the given interface only;
man page for ifconfig
ip # ip [OPTIONS] Newer command to monitor and set IP address and other network card–related information ip examples
# ip link show This example lists the available network device on the Linux server along with their Link status
route # route [OPTIONS] This program is obsolete. For replacement check ip route . ip route examples
ip route # ip route [OPTIONS] Manipulate route entries in the kernel routing tables keep information about paths to other networked nodes. ip route examples
# ip route show In this example we are printing the configured routes on the Linux server from the routing table
ethtool # ethtool [OPTIONS] DEVICE query or control network driver and hardware settings man page for ethtool
# ethtool -i eth0 In this example we are printing the interface details for eth0 . The interface name may vary based on the environment and configuration.
ping # ping OPTIONS DESTINATION ping is used to check the connectivity of remote computers man page for ping
# ping 192.168.0.100 In this example we are testing the connectivity between localhost and 192.168.0.100 server
traceroute # traceroute HOST Utility that helps you analyzing reachability of hosts on the network.
In most cases it is possible that due to firewall you may not get the list of hops towards the destination
man page for traceroute
# traceroute 192.168.0.100 In this example we are checking the route used to connect 192.168.0.100
nmap # nmap OPTIONS HOST Utility that helps you check which services are offered by an other host
It is used to check the list of open ports on destination server
man page for nmap
netstat # netstat [OPTIONS] Utility that helps you find out which services are offered by the local host
It will give you a list of ports which are used by different system services and any service from the network
man page for netstat
# netstat -tunlp In this example I am listing the listening TCP and UDP protocols on my Linux server
nmcli # nmcli [OPTIONS] nmcli is a command-line tool for controlling NetworkManager and reporting network status. nmcli examples
nmtui # nmtui nmtui is a curses‐based TUI application for interacting with NetworkManager
It is a graphical alternative to nmcli
nmtui examples
ss # ss [OPTIONS] ss is used to dump socket statistics. It allows showing information similar to netstat . It can display more TCP and state information than other tools.
When no option is used ss displays a list of open non-listening sockets (e.g. TCP/UNIX/UDP) that have established connection
man page for ss

Managing Partitions and Logical Volumes

One of the primary roles of system administrator would be to configure partitions, storage layouts in the Linux server. Here you can get the list of most used Linux commands for managing partitions and file systems.

Command Example/Syntax Comments For more details
df # df [OPTIONS] Report file system disk space usage
If no file name is given, the space available on all currently mounted file systems is shown
man page for df
fdisk # fdisk [OPTIONS] DEVICE fdisk is interactive program for creation and manipulation of partition tables. It understands GPT, MBR, Sun, SGI and BSD partition tables fdisk example
cfdisk # cfdisk [OPTIONS] DEVICE Display or manipulate a disk partition table man page for cfdisk
parted # parted parted is a program to manipulate disk partitions. It supports multiple partition table formats, including MS-DOS and GPT. parted example
pvcreate # pvcreate [OPTIONS] DEVICE Create LVM Physical Volume pvcreate example
# pvcreate /dev/sda In this example we are creating a physical volume using /dev/sda device
pvdisplay # pvdisplay DEVICE It shows the attributes of PVs, like size, physical extent size, space used for the VG descriptor area, etc man page for pvdisplay
pvs # pvs Display information about physical volumes
This can be used as an alternative to pvdisplay to display limited information of available physical volumes
man page for pvs
vgcreate # vgcreate [OPTIONS] It creates a new Volume Group on block devices (physical volume) vgcreate example
# vgcreate test_vg /dev/sda In this example we are create a new volume group «test_vg» by adding /dev/sda
Here /dev/sda is a new physical volume, you cannot use any existing device used by other logical volumes
vgdisplay # vgdisplay DEVICE vgdisplay shows the attributes of VGs, and the associated PVs and LVs man page for vgdisplay
vgs # vgs Display information about Volume Groups
This can be used as an alternative to vgdisplay to display limited information of available volume groups
man page for vgs
lvcreate # lvcreate [OPTIONS] This is used to create logical volumes lvcreate example
# lvcreate -L 1G -n test_lv1 test_vg In this example I am creating a logical volume test_lv1 of size 1GB under test_vg volume group
lvdisplay # lvdisplay DEVICE Display information about a logical volume man page for lvdisplay
lvs # lvs Display information about logical volumes in shorter output compared to lvdisplay command. You can use this as an alternative to lvdisplay man page for lvs
pvscan # pvscan [OPTIONS] Scans storage devices for the presence of LVM physical volumes.
It is used when a new physical volume metadata is not loaded and a pvscan can load the metadata of all the available PV
pvscan example
vgscan # vgscan [OPTIONS] Scans storage devices for the presence of LVM volume groups.
It can be used when any VG metadata is not visible and vgscan can scan the available VG
man page for vgscan
lvscan # lvscan [OPTIONS] Scans storage devices for the presence of LVM logical volumes.
It can be used when any LV metadata is not visible and lvscan can scan the available LV
man page for lvscan
vgchange # vgchange [OPTIONS] Changes the status from LVM volume groups and the volumes in it from active to inactive and vice versa vgchange example
# vgchange -ay In this example we are activating all the available volume groups. To deactivate all volume groups use vgchange -an
e2fsck # e2fsck [OPTIONS] check a Linux ext2/ext3/ext4 file system
We cannot perform a check on a mounted file system so normally this is performed during reboot or in single user mode
e2fsck example
tune2fs # tune2fs [OPTIONS] DEVICE tune2fs allows the system administrator to adjust various tunable filesystem parameters on Linux ext2, ext3, or ext4 filesystems. tune2fs example
dumpe2fs # dumpe2fs [OPTIONS] DEVICE prints the super block and blocks group information for the filesystem present on device. man page for dumpe2fs
mkfs. # mkfs.ext4
# mkfs.xfs
mkfs is used to build a Linux filesystem on a device, usually a hard disk partition. The device argument is either the device name (e.g. /dev/hda1, /dev/sdb2), or a regular file that shall contain the filesystem. create filesystem
lvextend # lvextend OPTIONS Add space to a logical volume lvextend example
vgextend # vgextend VGNAME PV Add physical volumes to a volume group vgextend example
resize2fs # resize2fs DEVICE The resize2fs program will resize ext2, ext3, or ext4 file systems. It can be used to enlarge or shrink an unmounted file system located on device resize2fs example
lsscsi # lsscsi [OPTIONS] list attached SCSI devices (or hosts) man page for lsscsi
lsblk # lsblk lsblk lists information about all available or the specified block devices. The lsblk command reads the sysfs filesystem and udev db to gather information man page for lsblk
blkid # blkid It prints the UUID valud of all the connected storage device. You can use this UUID to identify the storage device instead of using the physical name man page for blkid

Managing RPM and Software Repositories

With package manager such as yum, dnf, apt-get, the life of a system administrator becomes very easy. You can easily install, update, remove packages, upgrade server operating system and much more using these commands.

Command Example/Syntax Comments For more details
rpm # rpm [OPTIONS] FILE RPM Package Manager which can be used to build, install, query, verify, update, and erase individual software packages. man page for rpm
yum # yum [OPTIONS] FILE yum is short abbreviation for Yellow Dog Updater Modified.
It is obsolete now and is replaced by dnf in most recent Linux distributions.
YUM is a package manager for RPM-based Linux distributions
yum examples
yumdownloader # yumdownloader [OPTIONS] Allows you to download packages from a repository to your system without installing them yumdownloader examples
zypper # zypper [OPTIONS] FILE Package management utility in the SUSE works. Works more or less the same as yum.
The handling of repository is slightly different with zypper compared to yum
zypper examples
apt-get # apt-get [OPTIONS] FILE Ubuntu/Debian package management utility. Does a great job in installing and updating software. man page for apt-get
apt-cache # apt-cache [OPTIONS] FILE Tool that allows you to search for packages in the locally cached index files man page for apt-cache
dpkg # dpkg [OPTIONS] ACTION Original Debian package management utility, which has been made more or less obsolete by apt-get man page for dpkg
dpkg-scanpackages # dpkg-scanpackages [OPTIONS] Tool that allows you to convert a directory containing .deb packages into a repository. man page for dpkg-scanpackages
dnf # dnf [OPTIONS] DNF is the next upcoming major version of YUM, a package manager for RPM-based Linux distributions. dnf examples
createrepo # createrepo [OPTIONS] PATH createrepo is a program that creates a repomd (xml-based rpm metadata) repository from a set of rpms. createrepo examples
repoquery # repoquery [OPTIONS] This is part of yum-utils , Searches the available DNF repositories for selected packages and displays the requested information about them repoquery examples
repotrack # repotrack [OPTIONS] This is part of yum-utils , track packages and its dependencies and download them repotrack examples
reposync # reposync [OPTIONS] Synchronize packages of a remote DNF or YUM repository to a local directory. reposync examples
subscription-manager # subscription-manager [OPTIONS] Registers systems to a subscription management service and then attaches and manages subscriptions for software products subscription-manager examples

Manage logging

Now you know about most of the Linux commands to manager different areas of Linux server but you must be familiar of how logging works in Linux? This may vary based on different distribution, with old distros we used syslog-ng for logging but now almost all major distros have moved to rsyslog solution.

Command Example/Syntax Comments For more details
logger # logger [OPTIONS] MESSAGE logger makes entries in the system log.
When the optional message argument is present, it is written to the log.
logger examples
logrotate # logrotate [OPTIONS] Command that helps you to prevent log files from growing too big and rotate them after a certain amount of time or once a given size has been reached logrotate examples
journalctl # journalctl [OPTIONS] journalctl may be used to query the contents of the systemd journal as written by systemd-journald.service journalctl examples

Conclusion

In this cheat sheet tutorial I have tried to consolidate most used Linux commands by different types of experts across IT domains. I am yet to add commands for many other scenarios such as Managing Linux services, archiving, firewall etc but that would just make this tutorial infinite long. I may write another article based on the response I get on this one, even writers need motivation . So that I know people are reading and loving this cheat sheet then I may decide to spend some more time to write about the remaining Linux commands in another tutorial.

Looking forward for your feedback in the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

3 thoughts on “100+ Linux commands cheat sheet & examples”

useradd is discouraged. If you think it’s right, you can replace it with adduser.

Thank you. I’m a senior citizen at this point, and have moved in and out of IT at various times since the late 80’s and into the early 90’s, but each absence has pretty much wiped out any contemporaneous knowledge I thought I had, simply through the natural evolution of the art. It’s nice to know that there are still some familiar relics from the old days (lol) stubbornly refusing to be become irrelevant. You have very plainly and succinctly toured me down the hall of fame, showing me what relationships some of the unfamiliar items bear to the old-school stuff that used to make sense to me. I never was a master, but I wasn’t intimidated by the cli Linux, or the Microsoft Disk Operating System, hahaha. It requires a strong command of a subject to make the explanations and examples clear and understandable to less knowledgeable students, but you did just that. Kudos!

Thank you for your kind words and generous feedback.
I do try to explain these topics as much as possible assuming the one reading this may be a fresher so they may not have too much technical background knowledge.
Thanks again!

Источник

Читайте также:  Запуск проверки диска linux
Оцените статью