- How can I get the current working directory? [duplicate]
- 5 Answers 5
- How to display the current working directory in the Linux system?
- Syntax
- Exit Status
- Linux pwd Command
- PWD Syntax
- PWD Commands
- Display Current Directory
- PWD Flags
- pwd Version
- pwd -a
- pwd Help
- Echo $PWD
- PWD and OLDPWD command
- Conclusion
- About the author
- Syeda Wardah Batool
- Зачем нужна команда 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.
@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):
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\\\`\\\"\`\"`"
How to display the current working directory in the Linux system?
To print the current working directory, we use the pwd command in the Linux system.
pwd (print working directory) – The pwd command is used to display the name of the current working directory in the Linux system using the terminal. This is a shell building command that is available in most Unix shells such as Bourne shell, ash, bash, kash, and zsh.
Syntax
The general syntax of the pwd command is as follows −
A brief description of options available in the pwd command.
Sr.No. | Option & Description |
---|---|
1 | -L (logical) Display the value of $pwd if it names the current working directory |
2 | -P (physical) Display the physical directory, without any soft link |
3 | —help Displays a help message and then exits. |
By default, the pwd works as if -L option was specified.
Exit Status
The pwd command returns true unless an invalid option supplied or the current directory could not be read.
To display the current working directory, we use the pwd command in the Linux/Unix system as shown below.
vikash@tutorialspoint:~ pwd /home/vikash
To display the physical directory instead of symbolic links or soft links, we use -P option with the pwd command in the Linux/Unix system as shown below.
vikash@tutorialspoint:~ pwd -P /home/vikash
To display more about the pwd command we use -help option with the pwd command as shown below.
vikash@tutorialspoint:~ pwd --help
After execution of above command. It will be prompt a short description with available options available in the pwd command.
Linux pwd Command
The pwd is a helpful command for Linux users who are inexperienced and might get lost in the middle of directories.
The pwd is an abbreviated form of “Print Working Directory,” or we can call the Current Work Directory. It displays the name of the current directory with the root path.
It is the most frequently used built-in shell command by Linux system administrators.
PWD Syntax
The Syntax of pwd Command is:
PWD Commands
Here are a few most commonly used commands of pwd. Let’s check how they work in Linux System:
Display Current Directory
As my current working directory is the home directory, so it will print the home directory in the terminal.
To display the current working directory in Linux, use the command:
PWD Flags
The pwd command accepts two flags:
1. pwd –L
The -L flag is used to print symbolic links; in other words, in Linux, it points towards the file or folder where you are currently working in.
Let’s check its functionality:
Create a symbolic link in a home directory named Linuxhint and move the present directory to the newly created one.
Now, use the given command to check if it’s working:
2. pwd –P:
The -P command is used to print the actual path without any symbolic link.
pwd Version
The pwd command comes pre-installed. You can check the pwd version through the command-line by given command:
pwd -a
The following command will help you to display the list of all locations having executable name pwd:
pwd Help
When you use the help command, it will show you pwd command options.
To get it, use mentioned command in the terminal:
Echo $PWD
To store the path of the current directory, the echo $PWD command is used. It functions the same as the pwd –L command:
PWD and OLDPWD command
To get current and previous directory using one command, type:
Conclusion
We have seen a brief explanation of the pwd command and its examples. The pwd command is a widely used shell built-in command in Linux systems. It displays the current working directory on which the user is working.
About the author
Syeda Wardah Batool
I am a Software Engineer Graduate and Self Motivated Linux writer. I also love to read latest Linux books. Moreover, in my free time, i love to read books on Personal development.
Зачем нужна команда 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) — отображать физическую директорию без симлинков.
По умолчанию pwd ведёт себя так, как будто применена опция -L.
Чтобы понять, как работает аргумент -P, создадим директорию и симлинк, указывающий на эту директорию.
mkdir /tmp/directory ln -s /tmp/directory /tmp/symlink
Когда вы зайдёте в директорию /tmp/symlink и введёте команду pwd, вывод будет таким:
То есть текущей рабочей директорией становится /tmp/symlink. Если ввести команду pwd -P, вывод будет таким:
Симлинк (англ. Symlink, symbolic link) — символическая ссылка. Этим термином обозначают файл, в котором содержится абсолютный или относительный путь к другому файлу или директории.
То есть получаем директорию, на которую указывает симлинк.
Заключение
Текущая рабочая директория — директория, из которой вы вызываете команды в терминале. Чтобы отобразить текущую рабочую директорию, нужно использовать команду pwd. Если у вас остались вопросы, добро пожаловать в комментарии.