如何使用bashrc函数更改为文件目标目录?
问题描述:
我用这个小功能在我的.bashrc迅速看到我使用任何自定义工具来源:如何使用bashrc函数更改为文件目标目录?
function wvi()
{
vi `which $1`;
}
例如,fvi mysort
将打开我的工具mysort
的来源。
还有一件事我可以在这里使用 - 自动切换到实用程序存在于目录。
例如,
~ $ which mysort
/usr/bin/mysort
~ $
然后fvi mysort
应该做一个cd /usr/bin
,然后打开使用vi
。
如何将这个逻辑放在我的.basrhc
?是否有一些直接的实用工具,或者我需要首先得到路径,然后砍掉最后一个节点?
答
dirname `which mysort`
答
wvi() {
local file="$(which "$1")"
cd $(dirname "$file")
vi $(basename "$file")
cd - # return to the previous dir
}
当你定义函数()
你可以写你的函数在子shell中运行,所以你不必事后收拾你不需要function
关键字:
wvi() (
file="$(which "$1")"
cd $(dirname "$file")
vi $(basename "$file")
)
答
cd $(dirname `which $1`)
将工作在大多数情况下,虽然你可能要考虑如果用if语句(-h选项来测试内置查找符号链接)
if [ -h `which $1 ]; then
...
你可能想这样做的原因封闭像
cd $(dirname $(readlink `which $1`))
符号链接是VIM的行为有时会在打开符号链接时发生变化,具体取决于您打算如何处理打开的文件。
答
无需外部工具:
fvi() {
cd "${1%/*}"
vi "${1##*/}"
}
答
我会做这种方式
wvi() {(
p=$(which "$1")
cd "${p%/*}"
${EDITOR:-vi} "${p##/*/}"
)}
$ EDITOR而不是公正的情况下,用户可能更愿意使用Emacs抛出字面六( - :
什么是正确的方式来写`cd \`dirname \`哪个mysort \``?我认为不允许嵌套。 – Lazer 2010-11-22 16:13:25
@Lazer cd $(dirname` \`which mysort \``) - 可能是一个解决方案 – shuvalov 2010-11-22 16:15:50
J '$()`用于`cd $(dirname $(which mysort))` – 2010-11-22 17:10:17