简体   繁体   English

bash one-liner 切换到某个文件所在的目录

[英]A bash one-liner to change into the directory where some file is located

I often want to change to the directory where a particular executable is located.我经常想切换到特定可执行文件所在的目录。 So I'd like something like所以我想要类似的东西

cd `which python` 

to change into the directory where the python command is installed.切换到安装python命令的目录。 However, this is obviously illegal, since cd takes a directory, not a file.然而,这显然是非法的,因为 cd 需要一个目录,而不是一个文件。 There is obviously some regexp-foo I could do to strip off the filename, but that would defeat the point of it being an easy one-liner.显然我可以做一些 regexp-foo 来去除文件名,但这会破坏它是一个简单的单行的意义。

Here:这里:

cd $(dirname `which python`)

Edit:编辑:

Even easier (actually tested this time):更简单(这次实际测试过):

function cdfoo() { cd $(dirname `which $@`); }

Then "cdfoo python".然后是“cdfoo python”。

To avoid all those external programs ('dirname' and far worse, the useless but popular 'which') maybe a bit rewritten:为了避免所有这些外部程序('dirname' 和更糟糕的是,无用但流行的 'which')可能会被重写:

cdfoo() {
  tgtbin=$(type -P "$1")
  [[ $? != 0 ]] && {
    echo "Error: '$1' not found in PATH" >&2
    return 1
  }
  cd "${tgtbin%/*}"
}

This also fixes the uncommon keyword 'function' from above and adds (very simple) error handling.这也修复了上面不常见的关键字“function”,并添加了(非常简单的)错误处理。

May be a start for a more sphisticated solution.可能是一个更复杂的解决方案的开始。

For comparison:比较:

zsh:~% cd =vi(:h)
zsh:/usr/bin%

=cmd expands to the path to cmd and (:h) is a glob modifier to take the head =cmd 扩展到 cmd 的路径并且 (:h) 是一个全局修饰符来获取头部

zsh is write-only but powerful. zsh 是只写的,但功能强大。

这样的事情应该可以解决问题:

cd `dirname $(which python)`

One feature I've used allot is pushd / popd.我使用过的一项功能是 pushd/popd。 These maintain a directory stack so that you don't have to try to keep history of where you were if you wish to return to the current working directory prior to changing directories.它们维护一个目录堆栈,因此如果您希望在更改目录之前返回当前工作目录,则不必尝试保留您所在位置的历史记录。

For example:例如:

pushd $(dirname `which $@`)
...
popd

你可以使用这样的东西:

cd `which <file> | xargs dirname`

我添加了一些简单的错误处理,使 cdfoo() 的行为遵循 dirname 对于不存在/非路径参数的行为

function cdfoo() { cd $(dirname $(which $1 || ( echo . && echo "Error: '$1' not found" >&2 ) ));}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM