Linux fedora командная строка

Fedora Linux by Chris Tyler

Get full access to Fedora Linux and 60K+ other titles, with a free 10-day trial of O’Reilly.

There are also live events, courses curated by job role, and more.

Using the Command Line

Many system management tasks can be performed using either of the graphical user interfaces provided with Fedora (i.e., GNOME or KDE). However, most power users prefer the command line for system management work because they find it faster, more consistent between different versions of Linux, and easier to access remotely. The command line is also called a shell prompt, because the commands are processed by a program called a shell; the standard shell on a Fedora system is the Bourne-again shell (bash).

How Do I Do That?

If you are logged in to the system through the graphical user interface, access the command line through the terminal program. Select the menu option Applications→Accessories→Terminal (System→Terminal in KDE), or right-click on the desktop background and select Konsole under KDE.

Tip

If you find yourself using the terminal frequently, you can make it easier to launch: right-click on the Terminal option in the application menu and select “Add this launcher to panel.” A new panel icon will appear that will launch a new terminal when clicked.

If you have logged in to the system through a character-mode login screen or an SSH login, you will automatically be presented with a command line.

Understanding the shell prompt

The standard shell prompt looks like this:

This message is an invitation to enter a command. It shows the name of the user ( chris ), the computer being used ( concord2 ), and the current working directory within the filesystem ( ~ , meaning the user’s home directory). The last character of the prompt, $ , indicates that this is a normal user’s prompt, as opposed to the system administrator’s prompt, which ends with # .

Entering commands

To enter a command, simply type it, and then press Enter to execute it. The output from the command will appear after the command (scrolling the screen if necessary), and when the command is done a new prompt will be printed.

To edit a command line, use the left and right arrow keys to position within the line, and the Backspace and Delete keys to delete characters to the left or right of the cursor, respectively. To insert text, simply type it. You can press Enter with the cursor located anywhere on the line to execute the command. Other editing keys are available; Table 4-1 shows the most useful ones.

Table 4-1. Useful editing keys

Key or key sequence Description
Left arrow Move left one character.
Right arrow Move right one character.
Backspace Delete the character to the left of the cursor.
Delete Delete the character under/to the right of the cursor.
Ctrl-U Delete to the start of the line.
Ctrl-left arrow Move one word to the left.
Ctrl-right arrow Move one word to the right.
Esc, D Alt-D Delete to the end of the current word.
Esc, Backspace Alt-Backspace Delete to the start of the current word.
Home Ctrl-A Go to the start of the line.
End Ctrl-E Go to the end of the line.
Читайте также:  Проверить внешний ip адрес linux

Accessing previous commands

You can scroll through the history of previously entered commands using the up and down arrow keys. This enables you to easily re-enter a command, either exactly as you previously entered it or after editing.

You can also search for a previous command by pressing Ctrl-R (for reverse search) and then typing a few characters that appear in the command. For example, if you had at some previous point typed cat /etc/hosts and you pressed Ctrl-R and typed hos , the cat /etc/hosts command would appear (providing that no intervening commands contained the letter sequence hos ).

Obtaining a root prompt to enter commands as the superuser

The superuser account, root, is also called the privileged account, because it is not subject to the security restrictions that are applied to regular user accounts. root access is required for many system administration commands. Although it’s tempting to use the root account all the time on a single-user computer, it is unwise because Fedora assumes that you know what you’re doing and won’t ask for confirmation if you enter a dangerous command; it will just go ahead and execute it. If you’re using the root account, an incorrect command can cause a lot more damage than the same command executed in a normal account.

Although you can directly log in as a root user, it’s usually much safer to take on root privilege only when necessary, using the su (switch user) command:

$ su Password:  root-password  #

The shell prompt will change to end in a pound sign ( # ) instead of a dollar sign ( $ ) when you are in root mode. Press Ctrl-D or type exit to drop superuser access and return to your regular shell prompt.

Tip

In this book, I’ll use $ to indicate any normal user’s prompt, user $ to specifically indicate user ’s prompt, and # to indicate the root prompt. Avoid entering commands as root unnecessarily!

Linux error messages

Many Linux commands will output a message only if something goes wrong. For example, if you try to remove a file using the rm command, no message will be displayed if the file is successfully deleted, but an error message will be generated if the file does not exist:

$ rm  barbeque  rm: cannot remove \Qbarbeque': No such file or directory

Most error messages start with the name of the command that produced the message.

Logging out of a shell prompt

You can leave a shell by pressing Ctrl-D or typing exit . If you are using a terminal window and don’t have any programs running, you can simply close the window using the X button on the title bar.

How Does It Work?

The shell prompt is managed by bash, the Bourne-again shell. bash got its name from the fact that it is a successor to the original Unix shell, sh, which is also known as the Bourne shell (after its author, Steve Bourne). bash is a command editor, command interpreter, job controller, and programming language.

Читайте также:  Will linux play windows games

When bash receives a command, it splits it into words and uses globbing to expand any ambiguous filenames. bash next checks to see if the first word is a built-in command. If not, it treats it as an external command or program and searches a list of directories to find that program. It executes that program, passing the other words to the program as arguments. Almost all Linux commands are external programs.

Linux commands generally accept three types of arguments:

These start with a hyphen or double-hyphen ( — or — ) and modify the way the command operates. For example, the ls (list-files) command will include hidden files in its output if the -a argument is given, and will list detailed information about files when the -l option is specified. These options may be used individually, used together in any order, or combined after one hyphen if they all use a single hyphen:

$ ls -l $ ls -a $ ls -l -a $ ls -a -l $ ls -al $ ls -la

These have significance according to the order in which they are specified. For example, the cp (copy) command accepts two or more filenames:

$ cp   one two 

one is the name of the file being copied, and two is the name that will be given to the new copy. If you swap the position of the two arguments, the meaning of the command is changed. Options may be placed before, between, or after positional arguments; usually, the positions of the options don’t matter.

These combine options with positional arguments. An option with a value may be placed before or after other arguments, but the value must be placed directly after the option.

For example, the ls command accepts the -w option (width of output), which is specified along with a number indicating the desired width of output in characters. This can be combined with the -a and -l options in any order, as long as the number immediately follows the -w option:

$ ls -a -l -w 60 $ ls -w 60 -al $ ls -l -w 60 -a $ ls -l -w60 -a $ ls -alw60

Источник

Нужные команды Linux

Для работы в терминале требуется знать много команд, которые не часто бываю нужны, и поэтому со временем забываются. Размещаю на своем сайте самые «распространенные» команды linux, которые необходимы бывают при настройке системы.

В список включаю и некоторые полезные команды которые известны многим «линуксоидам», но пригодятся новичкам. Получится своего рода шпаргалка и полезное для тех кто только изучает эту тему.

Конечно же эти команды вы можете найти не только на моем сайте — информация широко распространена и известна, секрета не составляет. Делитесь этой информацией со своими друзьями и соратниками…

Главное это уметь узнать, найти справку по той или иной команде:

man ваша_команда — выводит справку по этой команде.

ваша_команда —help — выводит справку по этой команде.

Команды Linux для Red Hat, Fedora, CentOS

sudo dnf install имя_пакета — установить нужный пакет.
sudo dnf config-manager —add-repo адрес_репозитория — добавить сторонний репозиторий.
sudo dnf upgrade — обновить все пакеты до самых свежих.
sudo dnf remove — удалить ненужный пакет.
sudo dnf autoremove — удалить все ненужные зависимости.

Читайте также:  Linux remove package with dependencies

Команды Linux для Arch, Monjaro

sudo pacman -S имя_пакета — установить нужный пакет.
sudo yaourt -S имя_пакета — установить пакет из AUR, если его нет в основном репозитарии.
sudo pacman -Sy — обновить сведения о пакетах.
sudo pacman -Syu — обновить все пакеты до самых свежих.
sudo pacman -R имя_пакета — удалить ненужный пакет.
sudo pacman -Rs имя_пакета — удалить ненужный пакет со всеми зависимостями.

команды linux

Команды Linux для Debian, Ubuntu, Mint.

sudo apt install — установка пакета.
sudo apt-add-repository — добавление репозитория.
suto apt update — обновить сведения о пакетах.
sudo apt upgrade — обновить все пакеты.
sudo apt full-upgrade — полное обновление системы
sudo apt list — список пакетов.
sudo apt search — поиск пакетов по имени.
sudo apt show — показать подробную информацию о пакете.
sudo apt remove — удалить пакет.
sudo apt edit-sources — редактировать файл источников программного обеспечения.

Команды Linux для работы в терминале

man — команда для вызова справки к пакету или команде, вводим эту команду и после пробела команду или пакет, для которой нужна инструкция.

history — Отображает все недавно введённые вами команды.

cd — перейти в нужный вам каталог, cd адрес каталога.

clear — понятно из самого слова, очищает окно терминала.

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

sudo — дает права администратора на выполнение команды.

sudo su — все последующие действия в терминале будут выполнятся от имени администратора.

sudo gksudo — запускает приложение с графическим окружением от имени администратора.

Управление процессами (программами)

kill — Эта команда служит для принудительного завершения процессов. Нужно ввести kill PID_процесса . PID процесса можно узнать, введя top .

top — отображает перечень запущенных процессов, сортируя в зависимости от потребления ресурсов CPU.

xkill -введите её, затем щёлкните по тому окну, которое нужно закрыть.

killall — убивает процессы на которые вы укажете. К примеру — killall firefox

Работа с файлами и папками

file — выводит информацию о файле.

rename — переименовывает файл.

mkdir — создать новую папку там где вы находитесь.

Работаем с разделами носителей информации

lsblk — выводит информация о ваших дисках и разделах.

umount — демонтирует раздел.

df — показывает размер диска и размер свободного пространства.

free — сколько свободно и занято ОЗУ.

uname — информация о системе.

uname -a — информация о имени компьютера и ядре.

Управляем пользователями

whoami — отображает имя пользователя.

useradd — создает нового пользователя.

userdel — удаляет пользователя.

usermod — меняет учетную запись пользователя, переместить домашнюю папку пользователя, назначить дату когда заблокировать учетку и т.д.

Сеть

ip —help — инструкция по работе с командой ip , команда имеет большое применение и множество атрибутов введя эту команду вы сможете изучить и понять ее возможности и правила использования.

ip adress - показывает сведения о сетевых адресах.
ping - проверка подключения к сети, определенному адресу.
ip a - посмотреть сетевые интерфейсы и их mac адреса в том числе.

Использование утилиты ifconfig

Для Ubuntu и Debian необходимо установить предварительно пакет

или в других, таких как Manjaro

После установки используем команду

Исправляем битые или отложенные пакеты

Откройте терминал и в терминале попробуйте следующие команды, в той же последовательности:

sudo apt-get --fix-broken install

Перезагрузить или выключить систему, используем — systemctl

Источник

Оцените статью
Adblock
detector