Показать текущую папку linux

Зачем нужна команда pwd и что такое текущая рабочая директория

Зачем нужна команда pwd и что такое текущая рабочая директория главное изображение

Из этой статьи вы узнаете, как определить текущую рабочую директорию (current working directory) с помощью команды pwd.

Что такое текущая рабочая директория

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

По умолчанию, когда вы запускаете операционную систему Linux, текущим рабочим каталогом является домашняя директория. Изменить рабочую директорию можно с помощью команды cd.

Например, чтобы изменить текущую рабочую директорию на /tmp, используйте такую команду:

Путь к текущей рабочей директории может отображаться в оболочке командной строки.

Команда pwd выводит текущую рабочую директорию. Это одна из базовых и самых популярных команд в Linux. При вызове pwd выводится полный путь к текущей рабочей директории.

Команда pwd встроена в большинство современных командных оболочек, в том числе в Bash. Её поведение отличается от выполнения /bin/pwd. С помощью команды type можно получить все места, где есть pwd:

pwd is a shell builtin pwd is /bin/pwd 

Как показывает вывод, встроенная команда pwd имеет более высокий приоритет по сравнению с /bin/pwd. Поэтому она используется всякий раз, когда вы вводите в командую строку pwd. Если вы хотите использовать файл /bin/pwd, нужно указать в командной строке полный путь до него.

Как найти текущую рабочую директорию

Чтобы понять, в какой директории вы работаете в данный момент, введите в терминале pwd. Вывод может выглядеть так (название директории может отличаться):

Всё, что делает команда pwd — выводит значение переменной окружения PWD. Такой же вывод получится, если ввести в терминале:

получаем текущий рабочий каталог

Команда pwd принимает только два аргумента:

  • -L (—logical) — не разрешать симлинки.
  • -P (—physical) — отображать физическую директорию без симлинков.
Читайте также:  Asus x101ch linux mint

По умолчанию pwd ведёт себя так, как будто применена опция -L.

Чтобы понять, как работает аргумент -P, создадим директорию и симлинк, указывающий на эту директорию.

mkdir /tmp/directory ln -s /tmp/directory /tmp/symlink 

Когда вы зайдёте в директорию /tmp/symlink и введёте команду pwd, вывод будет таким:

То есть текущей рабочей директорией становится /tmp/symlink. Если ввести команду pwd -P, вывод будет таким:

Симлинк (англ. Symlink, symbolic link) — символическая ссылка. Этим термином обозначают файл, в котором содержится абсолютный или относительный путь к другому файлу или директории.

То есть получаем директорию, на которую указывает симлинк.

Заключение

Текущая рабочая директория — директория, из которой вы вызываете команды в терминале. Чтобы отобразить текущую рабочую директорию, нужно использовать команду pwd. Если у вас остались вопросы, добро пожаловать в комментарии.

Источник

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.

Читайте также:  Alt linux создание загрузочной флешки

@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.

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):

Читайте также:  Linux and dynamic disk

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\\\`\\\"\`\"`" 

Источник

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