[英]Set a bash variable each time the directory changes
I would like a variable available my bash shell similar to pwd
but equal to a section of the current working directory, rather than the whole path. 我想一个变量可用我的bash shell类似于pwd
但是等于当前工作目录的一部分,而不是整个路径。
ie, 即
$PWD=/a/b/c/d/e/f
$PATH_SECT=c/d/e
I have a prompt that displays this path already, but I would like to update a variable in the environment to this value each time I change directory. 我有一个提示,显示此路径,但我想每次更改目录时将环境中的变量更新为此值。
How could I do this? 我怎么能这样做?
You could use the promptcmd
function. 您可以使用promptcmd
函数。 From man bash
we learn that this function is executed just prior to showing the prompt. 从man bash
我们知道这个函数是在显示提示之前执行的。 It's empty by default (or rather, not defined). 默认情况下它是空的(或者更确切地说,未定义)。
A simple example: 一个简单的例子:
promptcmd(){
local p=$(pwd)
PATH_SECT=${p/\/a\/b\/}
}
You can use an alias
and a function in your .bashrc
: 您可以在.bashrc
使用alias
和函数:
alias cd="supercd" # call the function
function supercd(){
builtin cd "$@" # original cd
PATH_SECT=$(pwd) # or whatever
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.