- Основы Linux от основателя Gentoo. Часть 1 (1/4): BASH, основы навигации
- Предисловие
- Об этом руководстве
- Введение в bash
- Оболочка
- А у вас запущен bash?
- О bash
- Использование «cd»
- Абсолютные пути
- Относительные пути
- Использование ..
- Примеры относительных путей
- Понимание .
- cd и домашняя директория
- Другие домашние директории пользователей
- Об авторах
- Daniel Robbins
- Chris Houser
- Aron Griffis
- The linux users guide
Основы Linux от основателя Gentoo. Часть 1 (1/4): BASH, основы навигации
Предисловие
Об этом руководстве
Добро пожаловать в первую из четырех частей обучающего руководства по основам Linux, разработанного чтобы подготовить вас к сдаче экзамена Linux Professional Institute 101. В нем вы познакомитесь с bash (стандартной оболочкой командного интерпретатора в Linux), узнаете о большинстве возможностей таких стандартных команд Linux, как ls, cp и mv, разберетесь в инодах, жестких и символьных ссылках, и многом другом. К концу этого руководства у вас сформируется некий фундамент знаний, и вы будете готовы к изучению основ администрирования Linux. К концу всего курса (8 частей), у вас будет достаточно навыков, чтобы стать системным администратором Linux и пройти сертификацию LPIC Level 1 от Linux Professional Institute, если конечно захотите.
Данная первая часть руководства отлично подходит для новичков в Linux, а также для тех пользователей, кто хочет освежить или улучшить свое понимание фундаментальных концепций Linux, таких, как копирование и перемещение файлов, создание символических и жестких ссылок, а также стандартных команд обработки текста, включая конвейеры и перенаправления. По ходу мы также дадим множество советов, подсказок и трюков, что делает это руководство насыщенным и практичным, даже для тех, кто уже имеет солидный опыт работы с Linux. Для начинающих большая часть этого материала будет новой, но более продвинутые пользователи Linux найдут это руководство отличным средством, чтобы разложить свои фундаментальные навыки по полочкам у себя в голове.
Тем, кто изучал первую версию этого руководства с целью, отличной от подготовки к экзамену LPI, возможно, что вам не нужно его перечитывать. Однако, тем же, кто планирует сдавать экзамены, стоит обязательно просмотреть данную исправленную версию.
Введение в bash
Оболочка
Если вы уже использовали Linux ранее, то наверняка знаете, что после входа в систему вас приветствует приглашение, которое выглядит примерно так:
На практике приглашение, которое вы видите, может немного отличаться. Например, оно может содержать имя хоста, имя текущей рабочей директории, или все вместе. Не зависимо от того, как выглядит ваше приглашение, есть одна несомненная вещь: программа, которая выводит это приглашение, называется оболочка интерпретатора команд (от англ. shell — оболочка, он же командная строка или терминал — прим. пер.), и, вероятнее всего, вашей командной оболочкой будет ‘bash’.
А у вас запущен bash?
Вы можете убедиться, что используете bash, набрав:
Если строчка выше выдает ошибку, или ответ не соответствует, возможно, что вы запустили другую оболочку. В этом случае большая часть этого руководства все еще будет полезна, но было бы значительно лучше для вас переключиться на bash, ради подготовки к экзамену 101.
О bash
Bash — это акроним от Bourne-again-shell, от англ. «ещё-одна-командная-оболочка-Борна» или «рождённая-вновь-командная оболочка» (тут игра слов Bourne/born — прим. пер.), и является оболочкой по умолчанию для большинства Linux-систем. Задача оболочки получать от вас команды, через которые вы взаимодействуете с Linux-системой. После того, как вы закончили ввод команд, вы можете выйти из оболочки (exit) или закончить сеанс (logout), в этом случае вы увидите приглашение входа в систему.
Кстати, вы также можете выйти из оболочки bash нажав control-D в приглашении.
Использование «cd»
Вы, возможно, уже обнаружили, что пялиться на приглашение bash — не самое впечатляющее занятие в мире. Ну что ж, давайте узнаем как путешествовать по нашей файловой системе. В приглашении введите пожалуйста следующую команду (без $):
Вы только что сообщили bash, что хотите работать в директории /, также известной, как корневая; все директории в системе имеют форму дерева, и / является его вершиной, т.е. корнем (в информатике деревья растут наоборот, корень вверху, а ветки спускаются вниз — прим. пер.). cd устанавливает директорию, в которой вы в данный момент работаете, также известную как «текущая рабочая директория».
Чтобы узнать текущую рабочую директорию в bash нужно набрать:
В примере с cd, аргумент / называется путь. Он сообщает cd куда мы хотим отправиться. В частности, аргумент / это абсолютный путь, что значит, что он задает расположение относительно корня дерева файловой системы.
Абсолютные пути
Ниже несколько из них:
/dev
/usr
/usr/bin
/usr/local/bin
Как можно заметить, у всех абсолютных путей есть одна общая черта, они начинаются с /. Указывая, допустим, /usr/local/bin в качестве аргумента для cd, мы сообщаем, что хотим попасть в / директорию, затем в usr директорию внутри нее, и так далее в local и bin, вниз по дереву. Абсолютные пути всегда отсчитываются начиная от / сперва.
Относительные пути
Другой тип пути называется «относительный путь». bash, cd, и другие команды всегда интерпретируют их относительно текущей директории. Относительные пути НИКОГДА не начинаются с /. Так, если мы сначала переместимся в /usr:
То, затем мы можем использовать относительный путь local/bin, чтобы попасть в директорию /usr/local/bin:
Использование ..
Относительные пути могут также содержать одну или более «..» директории. Директория «..» специальная; она указывает на родительскую директорию. Так, продолжая с примера выше:
Как видно, наша текущая директория теперь /usr/local. Мы смогли переместиться «назад» на одну директорию относительно текущей, где были до того.
Кроме того, мы также можем использовать «..» в существующем относительном пути, позволяющем нам переместиться в директорию «рядом» с той, в которой находимся:
Примеры относительных путей
Относительные пути могут быть чуточку более сложными. Ниже несколько примеров, попробуйте самостоятельно догадаться, где вы окажитесь после набора каждой из этих команд.
А теперь наберите их и проверьте свои предположения. 😉
Понимание .
Перед тем как мы закончим изучение cd, есть несколько моментов, которые необходимо прояснить. Во-первых, есть еще одна специальная директория «.», которая означает «текущая директория». Хотя она и не используется с командой cd, но часто используется для выполнения программы из текущей директории, как в следующем примере:
В данном случае будет запущена исполняемая программа myprog, находящаяся в текущей рабочей директории.
cd и домашняя директория
Если бы мы хотели переместиться в нашу домашнюю директорию, то могли бы набрать:
Без каких либо аргументов cd переместит в вашу домашнюю директорию, которая будет /root для суперпользователя, или обычно /home/username (где username — имя пользователя в системе — прим.пер.) для любого другого пользователя. Но, что если мы хотим указать файл в нашей домашней директории? Может быть мы хотим передать путь к файлу в качестве аргумента нашей программе myprog. Если файл расположен в нашей домашней директории, мы можем набрать:
Однако, использования абсолютного пути вроде этого, не всегда удобно. К счастью, мы можем использовать символ
(тильда), чтобы проделать то же самое:
Другие домашние директории пользователей
Bash воспримет одиночную
как указатель на вашу домашнюю директорию, но вы также можете использовать её для указания на домашние директории других пользователей. Например, если мы хотели сослаться на файл под названием fredsfile.txt в домашней директории пользователя fred, то могли бы набрать:
Об авторах
Daniel Robbins
Дэниэль Роббинс — основатель сообщества Gentoo и создатель операционной системы Gentoo Linux. Дэниэль проживает в Нью-Мехико со свой женой Мэри и двумя энергичными дочерьми. Он также основатель и глава Funtoo, написал множество технических статей для IBM developerWorks, Intel Developer Services и C/C++ Users Journal.
Chris Houser
Крис Хаусер был сторонником UNIX c 1994 года, когда присоединился к команде администраторов университета Тэйлора (Индиана, США), где получил степень бакалавра в компьютерных науках и математике. После он работал во множестве областей, включая веб-приложения, редактирование видео, драйвера для UNIX и криптографическую защиту. В настоящий момент работает в Sentry Data Systems. Крис также сделал вклад во множество свободных проектов, таких как Gentoo Linux и Clojure, стал соавтором книги The Joy of Clojure.
Aron Griffis
Эйрон Гриффис живет на территории Бостона, где провел последнее десятилетие работая в Hewlett-Packard над такими проектами, как сетевые UNIX-драйвера для Tru64, сертификация безопасности Linux, Xen и KVM виртуализация, и самое последнее — платформа HP ePrint. В свободное от программирования время Эйрон предпочитает размыщлять над проблемами программирования катаясь на своем велосипеде, жонглируя битами, или болея за бостонскую профессиональную бейсбольную команду «Красные Носки».
Источник
The linux users guide
The Linux Documentation Project (LDP) is working on developing good, reliable documentation for the Linux operating system. The overall goal of the LDP is to collaborate in taking care of all of the issues of Linux documentation, ranging from online documentation (man pages, HTML, and so on) to printed manuals covering topics such as installing, using, and running Linux. Here is the Linux Documentation Project Manifesto and Copyright License for LDP works.
Translations of LDP works (languages other than English) can be found on the «Non-English Linux Info» links page.
Additional documentation (HOWTOs, FAQs, etc) can be found here.
Older and unmaintained (but still pertinent) guides can be found here.
Search the LDP documents from our search page.
Current / Maintained Guides |
Advanced Bash-Scripting Guide
version: | 10 |
author: | Mendel Cooper, |
last update: | Mar 2014 |
available formats: |
|
This document is both a tutorial and a reference on shell scripting with Bash. It assumes no previous knowledge of scripting or programming, but progresses rapidly toward an intermediate/advanced level of instruction . . . all the while sneaking in little nuggets of UNIX® wisdom and lore. It serves as a textbook, a manual for self-study, and as a reference and source of knowledge on shell scripting techniques. The exercises and heavily-commented examples invite active reader participation, under the premise that the only way to really learn scripting is to write scripts.
This book is suitable for classroom use as a general introduction to programming concepts.
Linux on the Road
Linux with Laptops, Notebooks, PDAs, Mobile Phones and Other Portable Devices
version: | 3.22 |
author: | Werner Heuser, |
last update: | Dec 2011 |
available formats: |
|
Though there are laptop, notebook, PDA and mobile phone related HOWTOs available already, this guide contains a concise survey of documents related to mobile computer devices. Also Linux features, such as installation methods for laptops, notebooks and PDAs as well as configurations for different (network) environments are described.
Although there are some caveats, Linux is a better choice for mobile computer devices than most other operating systems. Because it supports numerous installation methods, works in many heterogenoues environments and needs smaller resources.
Windows+OpenSolaris+CentOS Installation Guide
version: | 1.2 |
author: | Subhasish Ghosh, |
last update: | Jun 2009 |
available formats: |
|
Explains how three different operating systems can be installed and configured on a single hard disk. The reader may choose from: Microsoft Windows NT/2K/XP + OpenSolaris 2008.11 + CentOS 5.2. Only x86 & x86-compatible architecture multi-booting is discussed and GNU GRUB is the boot loader of choice.
Bash Guide for Beginners
version: | 1.11 |
author: | Machtelt Garrels, |
last update: | Dec 2008 |
ISBN: | 0-9744339-4-2 |
available formats: |
|
The Bash Guide for Beginners gets you started with Bash scripting and bridges the gap between the Bash HOWTO and the Advanced Bash Scripting Guide. Everybody who wants to make life easier on themselves, power users and sysadmins alike, can benefit from reading this practical course. The guide contains lots of examples and exercises at the end of each chapter, demonstrating the theory and helping you practice. Bash is available on a wide variety of UNIX, Linux, MS Windows and other systems.
Introduction to Linux — A Hands on Guide
version: | 1.27 |
author: | Machtelt Garrels, |
last update: | Jun 2008 |
ISBN: | 1596821124 |
available formats: |
|
This guide was created as an overview of the Linux Operating System, geared toward new users as an exploration tour and getting started guide, with exercises at the end of each chapter. For more advanced trainees it can be a desktop reference, and a collection of the base knowledge needed to proceed with system and network administration. This book contains many real life examples derived from the author’s experience as a Linux system and network administrator, trainer and consultant. We hope these examples will help you to get a better understanding of the Linux system and that you feel encouraged to try out things on your own.
GNU/Linux Command-Line Tools Summary
version: | 1.2 |
author: | Gareth Anderson, |
last update: | Apr 2006 |
available formats: |
|
This document is an attempt to provide a summary of useful command-line tools available to a GNU/Linux based operating system, the tools listed are designed to benefit the majority of users and have being chosen at the authors discretion. This document is not a comprehensive list of every existent tool available to a GNU/Linux based system, nor does it have in-depth explanations of how things work. It is a summary which can be used to learn about and how to use many of the tools available to a GNU/Linux-based operating system.
LDP Author Guide
version: | 4.8 |
authors: | Mark F. Komarinski, Jorge Godoy, David C. Merrill, Emma Jane Hogbin |
last update: | Apr 2006 |
available formats: |
|
This guide describes the process of submitting and publishing a document with The Linux Documentation Project (TLDP). It includes information about the tools, toolchains and formats used by TLDP. The document’s primary audience is new TLDP authors, but it also contains information for seasoned documentation authors.
The Linux Kernel Module Programming Guide
available versions: | 2.4 and 2.6 |
authors: | Peter Jay Salzman, Michael Burian, Ori Pomerantz |
last update: | May 2007 (kernel version 2.6) Jul 2004 (kernel version 2.4) |
available formats (kernel version 2.6): |
|
available formats (kernel version 2.4): |
|
A guide to programming Linux kernel modules.
The Linux System Administrators’ Guide
version: | 0.9 |
authors: | Lars Wirzenius, Joanna Oja, Stephen Stafford, and Alex Weeks |
last update: | July 2005 |
available formats: |
|
This is the third book in the main LDP series, and assumes knowledge of everything in the Installation and Users’ Guides. It will cover all of the aspects of keeping the system running, handling user accounts, backups, configuration of the system, installing and upgrading software, and more. Whereas some of this information is in the Installation Guide (just to get the system off the ground) this book should be much more complete.
Pocket Linux Guide
version: | 3.1 |
author: | David Horton, |
last update: | Apr 2005 |
available formats: |
|
The Pocket Linux Guide is for anyone interested in learning the techniques of building a GNU/Linux system from source code. The guide is structured as a project that builds a small diskette-based GNU/Linux system called Pocket Linux. Each chapter explores a small piece of the overall system explaining how it works, why it is needed and how to build it. After completing the Pocket Linux project, readers should possess an enhanced knowledge of what makes GNU/Linux systems work as well as the confidence to explore larger, more complex source-code-only projects.
Guide to Managing Media and Public Relations in the Linux Community
version: | 1.1 |
author: | The Linux Professional Institute Sheldon Rose |
last update: | Apr 2005 |
available formats: |
|
This guide provides useful information on how to generate positive public relations and news media coverage for Linux.
EVMS User Guide
version: | 2.4.0 |
authors: | Christine Lorenz, IBM Joy Goodreau, IBM Kylie Smith, IBM |
last update: | September, 2004 |
available formats: |
|
This book is designed to address user’s questions about Enterprise Volume Management System (EVMS) and provide a context for using EVMS. For additional information about EVMS or to ask questions specific to your distribution, the EVMS mailing lists are an excellent resource. You can view the list archives or subscribe to the lists from the EVMS Project web site.
version: | 0.18 |
author: | Binh Nguyen, |
last update: | April 2005 |
available formats: |
|
Linux Filesystem Hierarchy
version: | 0.65 |
author: | Binh Nguyen, |
last update: | July 2004 |
available formats: |
|
This document outlines the set of requirements and guidelines for file and directory placement under the Linux operating system according to those of the FSSTND v2.3 final (January 29, 2004) and also its actual implementation on an arbitrary system. It is meant to be accessible to all members of the Linux community, be distribution independent and is intended discuss the impact of the FSSTND and how it has managed to increase the efficiency of support interoperability of applications, system administration tools, development tools, and scripts as well as greater uniformity of documentation for these systems.
Custom Linux: A Porting Guide — Porting LinuxPPC to a Custom SBC
version: | 2.1 |
author: | Shie Erlich, |
last update: | Mar 2004 |
available formats: |
|
This guide describes a work in progress, to port Linux to a custom PowerPC-based board. This means making the operating system work on unfamiliar hardware. Anyone, who is on the same track might benefit from reading this paper, as it highlights the pitfalls and problematic points along the way.
Linux From Scratch
version: | 6.1.1 |
author: | Gerard Beekmans, |
last update: | Nov 2005 |
available formats: |
|
Derived from the popular Linux-From-Scratch-HOWTO, this book describes the process of creating your own Linux system from scratch from an already installed Linux distribution, using nothing but the sources of software that are needed.
The Bugzilla Guide
version: | 2.16.3 |
author: | Matthew P. Barnson, |
last update: | April 2003 |
available formats: |
|
This document is intended to be the comprehensive guide to the installation, administration, maintenance, and use of the Bugzilla bug-tracking system.
Linux Kernel 2.4 Internals
author: | Tigran Aivazian, |
last update: | August 2002 |
available formats: |
|
An introduction to the Linux 2.4 kernel. The author is working as senior Linux kernel engineer at VERITAS Software Ltd and wrote this book for the purpose of supporting the short training course/lectures he gave on this subject, internally at VERITAS.
Securing & Optimizing Linux: The Ultimate Solution
version: | 2.0 |
author: | Gerhard Mourani, |
last update: | July 2002 |
available formats: |
|
Mastering security with Linux and getting the maximum out of your system have never been easier. Securing & Optimizing Linux: The Ultimate Solution (v2.0) has been written and achieved with tightening security to an incomparable level in mind. One of its main features is the easy path from beginning to end in a smooth manner, step by step for beginners as well as for experts.
older version: Securing and Optimizing Linux Red Hat Edition — A Hands on Guide
version: | 1.3 |
author: | Gerhard Mourani, |
last update: | August 2000 |
available formats: |
|
Emacspeak User’s Guide
version: | 1.3 |
author: | Jennifer Jobst, |
last update: | July 2002 |
available formats: |
|
This document helps Emacspeak users become familiar with Emacs as an audio desktop and provides tutorials on many common tasks and the Emacs applications available to perform those tasks.
The Linux Cookbook: Tips and Techniques for Everyday Use
Removed at the author’s request.
The Linux Network Administrator’s Guide, Second Edition
version: | 1.1 |
authors: | Olaf Kirch and Terry Dawson |
last update: | March 2000 |
ISBN: | 1-56592-400-2 |
available formats: |
|
This book was written to provide a single reference for network administration in a Linux environment. Beginners and experienced users alike should find the information they need to cover nearly all important administration activities required to manage a Linux network configuration. The possible range of topics to cover is nearly limitless, so of course it has been impossible to include everything there is to say on all subjects. We’ve tried to cover the most important and common ones. We’ve found that beginners to Linux networking, even those with no prior exposure to Unix-like operating systems, have found this book good enough to help them successfully get their Linux network configurations up and running and get them ready to learn more.
Linux Administrator’s Security Guide
Removed at the request of the author (book is now more «dynamic»). Please access the Linux Administrator’s Security Guide at the following location: http://www.seifried.org/lasg/
Linux System Administration Made Easy
version: | 1.06 |
author: | Steve Frampton |
last update: | November 1999 |
available formats: |
|
The Linux Administration Made Easy (LAME) guide attempts to describe day-to-day administration and maintenance issues commonly faced by Linux system administrators.
This book can be purchased from bookstores, more information can be found here.
Older / Unmaintained (but still pertinent) Guides |
The Linux Network Administrators’ Guide
version: | 1.0 |
author: | Olaf Kirch |
last update: | March 1996 |
available formats: |
|
This guide supplements the System Administrators’ Guide and cover all of the diverse issues of networking under Linux, from UUCP to serial connections to TCP/IP. Many Linux users won’t have access to such a network, so this information is in a separate manual. It contains an intro to TCP/IP and UUCP (for those who have never used such networks before, lots of background information), TCP/IP, UUCP, SLIP, and DNS configuration, configuration of mail systems such as sendmail and Smail, setting up NNTP and news, and NFS.
The Linux Programmer’s Guide
version: | 0.4 |
authors: | B. Scott Burkett, Sven Goldt, John D. Harper, Sven van der Meer and Matt Welsh |
last update: | March 1996 |
available formats: |
|
The Linux Programmer’s Guide is meant to do what the name implies — It is to help Linux programmers understand the peculiarities of Linux. By its nature, this also means that it should be useful when porting programs from other operating systems to Linux. Therefore, this guide must describe the system calls and the major kernel changes which have effects on older programs like serial I/O and networking.
The Linux Users’ Guide
version: | beta-1 |
author: | Larry Greenfield |
last update: | December 1996 |
available formats: |
|
This book covers all of the user-end aspects of Linux, from sitting down at the first login session to using complex tools such as gcc, emacs, and so on. It assumes no previous Unix experience, so not only will it serve as an introduction to Linux, but to Unix in general as well. This manual won’t cover system administrator tasks (i.e. anything that needs to be done as root) — it’s for the J. Random User who has a working Linux system sitting in front of them.
The Linux Kernel Hackers’ Guide
version: | not available |
author: | Michael K. Johnson |
last update: | August 1998 |
available formats: |
|
This is an older, archived instance; complete with discussion threads (no posting or replying however).
Installation and Getting Started Guide
version: | 3.2 |
authors: | Matt Welsh and others |
last update: | March 1998 |
available formats: |
|
This book is for personal computer users who want to install and use Linux. The book assumes that you have basic knowledge about personal computers and operating systems like MS-DOS, but no previous knowledge of Linux or UNIX.
The Linux Kernel
version: | 0.8-3 |
author: | David A. Rusling |
last update: | January 1998 |
available formats: |
|
The kernel is at the heart of the operating system. This book is a guide to how the kernel fits together, how it works; a tour of the kernel.
Translated Guides |
Below is a table of translated guides that are available from pub/Linux/docs/ldp-archived/. Additional translations of LDP works and translated documentation not listed here may be found on the «Non-English Linux Info» page.
de | en | es | fr | it | ja | pl | pt | ru | sl |
Kernel Hackers Guide | en | ||||||||
Network Guide | en | es | |||||||
Programmers Guide | en | es | |||||||
System Administration Guide | en | es | fr | it | pt | ||||
Users Guide | en | es | it | ||||||
Debian Manuals and Guides (updated nightly) |
«An important part of any operating system is documentation, the technical manuals that describe the operation and use of programs. As part of its efforts to create a high-quality free operating system, the Debian Project is making every effort to provide all of its users with proper documentation in an easily accessible form.» — from Debian Documentation home page
Источник