bash 单行命令切换到某个文件所在的目录
我经常想更改到特定可执行文件所在的目录。 所以我想要
cd `which python`
更改为安装 python 命令的目录。 然而,这显然是非法的,因为 cd 使用的是目录,而不是文件。 显然,我可以使用一些 regexp-foo 来删除文件名,但这会破坏它作为简单单行的意义。
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. However, this is obviously illegal, since cd takes a directory, not a file. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这里:
编辑:
更容易(这次实际测试过):
然后是“cdfoo python”。
Here:
Edit:
Even easier (actually tested this time):
Then "cdfoo python".
为了避免所有这些外部程序(“dirname”,更糟糕的是,无用但流行的“which”),可能需要重写一下:
这也修复了上面不常见的关键字“function”,并添加了(非常简单的)错误处理。
可能是更复杂的解决方案的开始。
To avoid all those external programs ('dirname' and far worse, the useless but popular 'which') maybe a bit rewritten:
This also fixes the uncommon keyword 'function' from above and adds (very simple) error handling.
May be a start for a more sphisticated solution.
为了比较:
=cmd 扩展为 cmd 的路径,(:h) 是一个 glob 修饰符,用于获取头部
zsh 是只写的,但功能强大。
For comparison:
=cmd expands to the path to cmd and (:h) is a glob modifier to take the head
zsh is write-only but powerful.
类似的东西应该可以解决问题:
something like that should do the trick :
我使用过的一项功能是 pushd / popd。 它们维护一个目录堆栈,这样如果您希望在更改目录之前返回到当前工作目录,则不必尝试保留您所在位置的历史记录。
例如:
One feature I've used allot is 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:
你可以使用这样的东西:
You could use something like this:
我添加了一些简单的错误处理,使 cdfoo() 的行为遵循 dirname 对于不存在/非路径参数的行为
I added a bit of simple error handling that makes the behavior of cdfoo() follow that of dirname for nonexistent/nonpath arguments