How can I get the current working directory?
There's no need to do that, it's already in a variable:
$ echo $PWD
/home/terdon
The PWD
variable is defined by POSIX and will work on all POSIX-compliant shells:
PWD
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 {PATH_MAX} 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):
var=$(command)
or
var=`command`
Of the two, the $()
is preferred since it is easier to build complex commands like:
command0 $(command1 $(command2 $(command3)))
dir=$(pwd)
This is more portable and preferred over the backticks method.
Using $()
allow you to nest the commands
eg : mech_pwd=$(pwd; echo in $(hostname))
You can either use the environment variable $PWD
, or write something like:
dir=`pwd`