Dynamically computed Bash variable
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?
PWD is a variable already set to your current directory by bash, ksh and other shells.
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
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
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.
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")")"
.
精彩评论