Navigating the bash shell with pushd and popd

5 ответов

138

означает «внутренний разделитель полей». Он используется оболочкой для определения того, как выполнять разбиение на слова, т.е. е. как распознать границы слов.

Попробуйте это в оболочке, например bash (другие оболочки могут обрабатывать это иначе, например zsh):

Значение по умолчанию для состоит из пробельных символов (точнее: пробел, табуляция и новая строка). Каждый символ может быть границей слов. Итак, со значением по умолчанию , цикл выше будет печатать:

Другими словами, оболочка считает, что пробел является границей слов.

Теперь попробуйте установить перед выполнением цикла. На этот раз результат:

Теперь оболочка также разбивает на слова, но теперь он обрабатывает только двоеточие как границу слова.

Первый символ является специальным: он используется для разграничения слов в выводе при использовании специальной переменной (пример, взятый из Расширенное руководство по созданию скриптов Bash , где вы также можете найти дополнительную информацию о специальных переменных, подобных этому):

Сравнить с:

Обратите внимание, что в обоих примерах оболочка по-прежнему будет обрабатывать все символы , и как границы слов. Единственное, что меняется, это поведение

Еще одна важная вещь, которую нужно знать, — это так называемое «IFS whitespace» . В принципе, как только содержит пробельные символы, ведущее и завершающее пробелы удаляются из строки, подлежащей разбивке, перед ее обработкой, а последовательность последовательности последовательных пробельных символов также ограничивает поля , Однако это относится только к тем символам пробела, которые фактически присутствуют в .

Например, давайте посмотрим на строку (пробел и два пробела между и ).

С он будет разделен на четыре поля: , , (пустая строка) и (опять же, два пробела между и )

Обратите внимание на начальное и конечное пробелы в последнем поле. С он будет разделен на пять полей: , , (пустая строка), и

Отсутствуют ведущие и конечные пробелы.

Обратите внимание, что несколько последовательных пробельных символов ограничивают два поля во втором примере, в то время как несколько последовательных двоеточий не имеют (поскольку они не являются пробельными символами). Что касается , то есть синтаксис , также поддерживаемый , code>, и FreeBSD (с вариантами между всеми оболочками)

Цитирование справочной страницы bash:

Что касается , то есть синтаксис , также поддерживаемый , code>, и FreeBSD (с вариантами между всеми оболочками). Цитирование справочной страницы bash:

— это escape-последовательность для новой строки, поэтому заканчивается установкой одного символа новой строки.

16

Внутри одиночных кавычек, некоторые персонажи оцениваются специально. Например, переводится в новую строку.

Итак, эта конкретная строка назначает новую строку переменной IFS. IFS, в свою очередь, является специальной переменной в bash: Internal Field Separator. Как говорит , он

11

Короче говоря, назначить newline переменной .

Конструкция

— это механизм цитирования, который используется для декодирования ANSI C, как escape-последовательности. Этот синтаксис исходит из и переносится в современную оболочку, например , , , .

Этот синтаксис не определяется POSIX, но был принят для .

-1

Trick с (и поведение Readline при неоднозначном завершении), используемое для эмуляции пополнения меню с описаниями:

-2

Я предпочел объяснить через пример:
Suppsoe вы хотите использовать cp или mv или другой файл, IFS пуст defualt, когда ваши файлы имеют метасимвол или пробел, например:
или , У вас будет probelm, потому что:
Linux рассматривает отдельный параметр и Administartion рассматривает отдельный параметр. В bash есть встроенная переменная , тогда вы можете инициализировать до , Затем bash отбрасывает любой метасимвол и пробел между именем файла, например:

Directory Stack #

The directory stack is a list of directories you have previously navigated to. The contents of the directory stack can be seen using the command. Directories are added to the stack when changing to a directory using the command and removed with the command.

The current working directory is always on the top of the directory stack. The current working directory is the directory (folder) in which the user is currently working in. Each time you interact with the command line, you are working within a directory.

The command allows you to find out what directory you are currently in.

When navigating through the file system, use the key to autocomplete the names of directories. Adding a slash at the end of the directory name is optional.

, and are shell builtins, and its behavior may slightly differ from shell to shell. We will cover the Bash builtin version of the commands.

pushd Command #

The syntax for the command is as follows:

For example to save the current directory to the top of the directory stack and change to you would type:

On success, the command above will print the directory stack. is the directory in which we executed the command. The tilde symbol means home directory.

first saves the current working directory to the top of the stack and then navigates to the given directory. As the current directory must always be on the top of the stack, once changed the new current directory goes to the top of the stack but it is not saved in the stack. To save it you must invoke from it. If you use to change to another directory, the top item of the stack will be lost,

Let’s add another directory to the stack:

To suppress changing to directory, use the option. For example, to add the directory to the stack but not change into it you would type:

As the current directory (which is always in the top) is not changed, the directory is added second from the top of the stack:

The accepts two options, and that allows you to navigate to directory of the stack. The option changes to element of the stack list counting from left to right starting with zero. When is used the direction of the count is from right to left.

To better illustrate the options, let’s print the current directory stack:

The output will show an indexed list of the directory stack:

If you want to change to the directory, and bring it to the top of the stack you will use one of the following.

When counting from top to bottom (or left to right), the index of the directory is .

When counting from bottom to top the index of the directory is .

When used without any argument, will toggle the top two directories and makes the new top the current directory. This is the same as when using the command.

Что я помню из команд bash

Это те команды, которые я использую чаще всего в Linux (начиная от самых часто используемых к самым редко используемым). Как я уже писал раньше, знание всего горстки команд поможет выполнять большой набор необходимых программируемых задач.

  • изменить директорию
  • вывести директорию в виде списка (подробного)
  • или редактор командной строки
  • создать новый пустой файл
  • скопировать файл или директорию (и всё их содержимое)
  • переместить или переименовать файл
  • удалить файл
  • удалить файл или папку без возможности восстановления
  • вывести текущую рабочую директорию
  • или или или вывести в STDOUT содержимое файла
  • создать пустую директорию
  • найти строку в любом файле этой директории или дочерних директориях
  • отобразить разделенный запятыми файл в виде столбцов
  • соединиться с удалённой машиной
  • показать структуру директории на 3 уровнями вглубь (с размерами файлов и включая скрытые директории)
  • (или ) диспетчер задач
  • пакетный менеджер Python для установки пакетов в ~/.local/bin
  • push/pop/view директорию в стек + изменить обратно на последнюю директорию
  • заменить строку в файле
  • заменить строку для каждого файла в этой и дочерней папках с именем типа *.txt
  • создать новую сессию терминала без создания нового окна
  • загрузить веб-страницу или веб-ресурс
  • отправить HTTP-запрос на веб-сервер
  • вывести список всего содержимого директории и её дочерних директорий рекурсивно

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

Я считаю хорошей практикой хранить список команд, которые полезны в определённых ситуациях, даже если подобные ситуации случаются редко (например, какой процесс блокирует конкретный сетевой порт). Вот несколько нестандартных команд, которые у меня всегда под рукой:

  • вывести список дескрипторов открытых файлов ( — флаг для сетевых интерфейсов)
  • вывести список открытых интернет/UNIX сокетов и связанной с ними информации
  • транслировать текущий диск, сеть, активность CPU и другое
  • найти hostname для удалённого IP-адреса
  • отследить системные вызовы программы ( — флаг для фильтрования конкретных системных вызовов)
  • вывести текущие активные процессы
  • проверить тип файла (например исполняемый, бинарный, текстовый файл с кодировкой ASCII)
  • информация о ядре ОС
  • информация об ОС
  • проверить hostname текущего компьютера (например, название, чтобы другие компьютеры могли иметь доступ к вашему)
  • визуализировать форки процессов
  • исполнить команду и составить статистику о том, сколько времени потребовалось на исполнение
  • отправить процесс в текущий tty в background и обратно на передний план
  • посчитать количество уникальных слов в файле
  • количество строк в файле
  • показать размер на диске для директорий и их содержимого
  • вывести содержимое заархивированного текстового файла
  • скопировать файл с удалённого на локальный сервер или наоборот
  • показать инструкцию, (т.е. документацию) для команды (но скорее всего легче использовать Google)

Перевод: Наталия Басс

Originally published at ru.hexlet.io.

Removing directories from the stack

Your stack is, obviously, not immutable. You can add to it with pushd or remove items from it with popd.

For instance, assume you have just used pushd to add ~/one to your stack, making ~/one your current working directory. To remove the first (or «zeroeth,» if you prefer) element:

$ pwd
~one
$ popd +tmp ~onetwothree ~one ~onetwothreefourfive ~onetwothreefour
$ pwd
~one

Of course, you can remove any element, starting your count at 0:

$ pwd ~one
$ popd +2 tmp ~onetwothree ~onetwothreefourfive ~onetwothreefour
$ pwd ~one

You can also use popd from the back of your stack, again starting with 0. For example, to remove the final directory from your stack:

$ popd -0tmp ~onetwothree ~onetwothreefourfive

When used like this, popd does not change your working directory. It only manipulates your stack.

Псевдонимы директорий

  • Текущая директория (где я?):
  • Родительская директория текущей директории:
  • Домашняя директория пользователя:
  • Корень файловой системы (или родитель всех родителей):

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

Таким же способом, чтобы скопировать файл, расположенный в “/path/to/file.txt” в текущую директорию, нужно ввести (заметьте, что в конце команды точка). Поскольку это всего лишь псевдонимы, вместо них может использоваться реальное имя пути.

STDIN / STDOUT

Всё, что вы пишите в окне и подтверждаете (с помощью ENTER), называется стандартным вводом (STDIN).

Всё, что программа выводит в ответе в терминал (например текст из файла), называется стандартным выводом (STDOUT)

Пожалуйста, помогите c переводом:

1. Lol when @hartdenton develops his coachella polaroids
2. Usting @melton as my bitch for gueen
3. Trying to pack for LA
4. Fresh nails wha dis
5. Me once my motor cycle license is done this summer
6. So cute
7. The detail. . . even down to my snake rings. . . Amazing!

Английский-Русский

Giving a definition of the term “comedy”, one may face some difficulties as it’s one of the most complex categories of aesthetics. Comedy is historically volatile, it depends on the context and has a social nature. The laughter is not always a sight of comedy, and comedy is not always defined by laughter. It is circumstances, sharpening the contradictions and helping to reveal its social nature

Английский-Русский

Measuring the positive side of the work–family interface: Development and validation of a work–family enrichment scale

Английский-Русский

Mendeleev was foreshadowed in his great generalization by De Chancourtois’s helix of elements of 1863, J.A.R. New-lands’s *law of octaves* (1864-5)-which uncovered periodicity in the 8th elements of his chemical groupings — and W. Odling’s work, which suggested that recurrent chemical properties in elements arranged according to atomic weight could not be accidental.

Английский-Русский

Adding to the stack

You can continue to navigate your stack in this way, and it will remain a static listing of your recently visited directories. If you want to add a directory, just provide the directory’s path. If a directory is new to the stack, it’s added to the list just as you’d expect:

$ pushd tmptmp ~onetwothree ~one ~onetwothreefourfive ~onetwothreefour

But if it already exists in the stack, it’s added a second time:

$ pushd ~one
~one tmp ~onetwothree ~one ~onetwothreefourfive ~onetwothreefour

While the stack is often used as a list of directories you want quick access to, it is really a true history of where you’ve been. If you don’t want a directory added redundantly to the stack, you must use the +N and -N notation.

Pushd and popd in the real world

The pushd and popd commands are surprisingly useful. Once you learn them, you’ll find excuses to put them to good use, and you’ll get familiar with the concept of the directory stack. Getting comfortable with pushd was what helped me understand git stash, which is entirely unrelated to pushd but similar in conceptual intangibility.

Using pushd and popd in shell scripts can be tempting, but generally, it’s probably best to avoid them. They aren’t portable outside of Bash and Zsh, and they can be obtuse when you’re re-reading a script (pushd +3 is less clear than cd $HOME/$DIR/$TMP or similar).

Navigating the stack

Once you’ve built up a stack, you can use it as a collection of bookmarks or fast-travel waypoints. For instance, assume that during a session you’re doing a lot of work within the ~/one/two/three/four/five directory structure of this example. You know you’ve been to one recently, but you can’t remember where it’s located in your pushd stack. You can view your stack with the +0 (that’s a plus sign followed by a zero) argument, which tells pushd not to change to any directory in your stack, but also prompts pushd to echo your current stack:

$ pushd +
~onetwothreefour ~onetwothree ~one ~onetwothreefourfive

Alternatively, you can view the stack with the dirs command, and you can see the index number for each directory by using the -v option:

$ dirs -v  ~onetwothreefour1  ~onetwothree 2  ~one3  ~onetwothreefourfive

The first entry in your stack is your current location. You can confirm that with pwd as usual:

$ pwd
~onetwothreefour

Starting at 0 (your current location and the first entry of your stack), the second element in your stack is ~/one, which is your desired destination. You can move forward in your stack using the +2 option:

$ pushd +2
~one ~onetwothreefourfive ~onetwothreefour ~onetwothree
$ pwd
~one

This changes your working directory to ~/one and also has shifted the stack so that your new location is at the front.

You can also move backward in your stack. For instance, to quickly get to ~/one/two/three given the example output, you can move back by one, keeping in mind that pushd starts with 0:

$ pushd -0
~onetwothree ~one ~onetwothreefourfive ~onetwothreefour

Navigating with popd

The default behavior of popd, given no arguments, is to remove the first (zeroeth) item from your stack and make the next item your current working directory.

This is most useful as a quick-change command, when you are, for instance, working in two different directories and just need to duck away for a moment to some other location. You don’t have to think about your directory stack if you don’t need an elaborate history:

$ pwd
~one
$ pushd ~onetwothreefourfive
$ popd
$ pwd
~one

You’re also not required to use pushd and popd in rapid succession. If you use pushd to visit a different location, then get distracted for three hours chasing down a bug or doing research, you’ll find your directory stack patiently waiting (unless you’ve ended your terminal session):

$ pwd ~one
$ pushd tmp
$ cd {etc,var,usr}; sleep 2001...
$ popd
$ pwd
~one
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector