Linux вывести путь до текущей директории

How can I get the current working directory? [duplicate]

I want to have a script that takes the current working directory to a variable. The section that needs the directory is like this dir = pwd . It just prints pwd how do I get the current working directory into a variable?

This is not a duplicate of the question for which it is currently marked as one. The two questions should be compared, at least, based on their titles (as well as their answers). That the answer to this question is already covered by another is, or should be, irrelevant.

@KennyEvitt actually, one of the main reasons we close is precisely because an answer has been given elsewhere. And, in fact, the main question here is actually how to assign the output of a command to a variable, which is covered by the dupe. I have also given the answer to this specific case, so all bases are covered. There would be no benefit in opening this again.

@terdon As a resource available, and intended, for the entire population of Unix & Linux users, this is a valuable question, even if the original asker really just needed an answer already covered elsewhere. If anything, I think this question should be edited to more closely match its title and it should be re-opened, not to allow further activity, but to not imply that this question is ‘bad’.

@KennyEvitt closing as a duplicate in no way implies that the question is bad! This question will remain here, answered, for ever. If you really want to know how to get the current working directory, you will find your answer here. If you just want to know how to save the output of a command in a variable, you will also find the answer here by following the link to the dupe. In any case, this isn’t really something I should do alone, if you feel strongly that it should be reopened, please open a discussion on Unix & Linux Meta where such things should be resolved.

Читайте также:  Сервер печати linux настройка

5 Answers 5

There’s no need to do that, it’s already in a variable:

The PWD variable is defined by POSIX and will work on all POSIX-compliant shells:

Set by the shell and by the cd utility. In the shell the value shall be initialized from the environment as follows. If a value for PWD is passed to the shell in the environment when it is executed, the value is an absolute pathname of the current working directory that is no longer than bytes including the terminating null byte, and the value does not contain any components that are dot or dot-dot, then the shell shall set PWD to the value from the environment. Otherwise, if a value for PWD is passed to the shell in the environment when it is executed, the value is an absolute pathname of the current working directory, and the value does not contain any components that are dot or dot-dot, then it is unspecified whether the shell sets PWD to the value from the environment or sets PWD to the pathname that would be output by pwd -P. Otherwise, the sh utility sets PWD to the pathname that would be output by pwd -P. In cases where PWD is set to the value from the environment, the value can contain components that refer to files of type symbolic link. In cases where PWD is set to the pathname that would be output by pwd -P, if there is insufficient permission on the current working directory, or on any parent of that directory, to determine what that pathname would be, the value of PWD is unspecified. Assignments to this variable may be ignored. If an application sets or unsets the value of PWD, the behaviors of the cd and pwd utilities are unspecified.

For the more general answer, the way to save the output of a command in a variable is to enclose the command in $() or ` ` (backticks):

Читайте также:  Xerox b210 linux driver

Of the two, the $() is preferred since it is easier to build complex commands like:

command0 "$(command1 "$(command2 "$(command3)")")" 

Whose backtick equivalent would look like:

command0 "`command1 \"\`command2 \\\"\\\`command3\\\`\\\"\`\"`" 

Источник

Команда pwd Linux

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

При запуске терминала текущей папкой считается домашний каталог пользователя. Если программу запускать из определенной папки, то ее текущей папкой будет та папка, из которой ее запустили.

Команда pwd в Linux

Синтаксис команды очень простой:

Вот основные опции, которые вы можете использовать для настройки вывода утилиты:

  • -L, —logical — брать директорию из переменной окружения, даже если она содержит символические ссылки;
  • -P — отбрасывать все символические ссылки;
  • —help — отобразить справку по утилите;
  • —version — отобразить версию утилиты.

Дальше рассмотрим несколько примеров работы с командой. Для того чтобы просто посмотреть текущую папку Linux достаточно выполнить pwd без параметров:

Также у команды есть одна опция -P. Если по пути к текущей папке есть символические ссылки, то утилита покажет полный путь без учета символических ссылок:

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

Чтобы узнать текущую папку в скрипте не обязательно использовать эту команду. Достаточно обратится к переменной окружения PWD:

Но также можно записать результат выполнения команды pwd linux в переменную:

Читайте также:  Калькулятор для linux ubuntu

Выводы

Команда pwd Linux используется достаточно редко, намного чаще нам нужно менять текущую папку. Для этого применяется команда cd. Как видите, все очень просто.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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