Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define pwd as a variable in Unix shell

Tags:

shell

unix

pwd

I tried the following but it didn't work.

dir=$pwd
echo $dir

/bin/env/####/ --id --edition dir- $dir

I want to paste the current working directory into the above script.

like image 702
Sathish Avatar asked Dec 30 '13 12:12

Sathish


People also ask

Is pwd a shell variable?

pwd is shell built-in command(pwd) or an actual binary(/bin/pwd). $PWD is an environment variable which stores the path of the current directory.

How do you declare a variable in UNIX shell?

Unix Command Course for BeginnersA variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data. A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables.

How can I get pwd in shell?

To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd. This tells you that you are in the user sam's directory, which is in the /home directory. The command pwd stands for print working directory.


2 Answers

The current directory is already in a variable, called PWD, and it is automatically set by the shell:

echo "$PWD"

You could also:

dir=$(pwd)
echo "$dir"

Or you could use these in your script without storing in additional variables:

/bin/env/####/ --id --edition-dir "$PWD"
/bin/env/####/ --id --edition-dir "$(pwd)"

For your information: every time you change directory, whether in an interactive shell or a script, the shell sets the value of the PWD variable to the current directory, and the value of OLDPWD to the previous directory.

Well, usually. As @WilliamPursell pointed out, OLDPWD is not standard, so it might not be available in all shells.

like image 183
janos Avatar answered Oct 01 '22 13:10

janos


try this:

dir="$PWD"

or

dir="$(pwd)"

you may want to have double quotes too if your path contained special chars, like spaces.

like image 36
Kent Avatar answered Oct 01 '22 13:10

Kent