1

I have several similarly structured directory trees. something like: ~/ Tree1/ src/
bin/ Tree2/ src/ bin/

When I somewhere below Tree1/src I want to work with Tree1/bin. When I somewhere below Tree2/src I want to work with Tree2/bin.

Is there a way to define a shell variable whose value depends on my current working directory?

5 Answers 5

3

PWD is a variable already set to your current directory by bash, ksh and other shells.

Sign up to request clarification or add additional context in comments.

Comments

1

cwd=$(pwd) should do the trick. It assigns the output of print working directory (pwd) to a variable.

To replace ~Tree1/src/dir1/dir2 with ~Tree1/bin you could do

bindir=$(pwd | sed 's/src.*/bin/')

See also Command Substitution

Comments

1

As jlliagre stated, bash (as many other modern shells) stores the current working directory in $PWD; if it is Tree1/src/some/other/directory, then you can extract "Tree1/bin" from it by just using "parameter expansion":

$ echo $PWD
Tree1/src/some/other/directory

$ echo ${PWD%%src*}bin
Tree1/bin

Comments

0

Generally $PWD variable (Present Working Directory) contains the path to the current directory. If this variable is not defined, you can use the pwd command that will return the current path.

Comments

0

Two other definitions of "current" include the directory you were in when the script was started (which is the value of start_dir="$PWD" at the start of the file, no matter where the script is) and the directory of the script itself - script_dir="$(dirname -- "$(readlink -f -- "$0")")".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.