2010-11-22 59 views
1

我用这个小功能在我的.bashrc迅速看到我使用任何自定义工具来源:如何使用bashrc函数更改为文件目标目录?

function wvi() 
{ 
    vi `which $1`; 
} 

例如,fvi mysort将打开我的工具mysort的来源。

还有一件事我可以在这里使用 - 自动切换到实用程序存在于目录。

例如,

~ $ which mysort 
/usr/bin/mysort 
~ $ 

然后fvi mysort应该做一个cd /usr/bin,然后打开使用vi

如何将这个逻辑放在我的.basrhc?是否有一些直接的实用工具,或者我需要首先得到路径,然后砍掉最后一个节点?

回答

2
dirname `which mysort` 
+0

什么是正确的方式来写`cd \`dirname \`哪个mysort \``?我认为不允许嵌套。 – Lazer 2010-11-22 16:13:25

+0

@Lazer cd $(dirname` \`which mysort \``) - 可能是一个解决方案 – shuvalov 2010-11-22 16:15:50

+3

J '$()`用于`cd $(dirname $(which mysort))` – 2010-11-22 17:10:17

0
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") 
) 
0
cd $(dirname `which $1`) 

将工作在大多数情况下,虽然你可能要考虑如果用if语句(-h选项来测试内置查找符号链接)

if [ -h `which $1 ]; then 
    ... 

你可能想这样做的原因封闭像

cd $(dirname $(readlink `which $1`)) 

符号链接是VIM的行为有时会在打开符号链接时发生变化,具体取决于您打算如何处理打开的文件。

1

无需外部工具:

fvi() { 
    cd "${1%/*}" 
    vi "${1##*/}" 
} 
1

我会做这种方式

wvi() {(
    p=$(which "$1") 
    cd "${p%/*}" 
    ${EDITOR:-vi} "${p##/*/}" 
)} 

$ EDITOR而不是公正的情况下,用户可能更愿意使用Emacs抛出字面六( - :