简体   繁体   English

cd使用别名进入可执行目录

[英]cd into executable directory using alias

I am trying to write an alias that allows me to the current directory to the executable directory. 我试图写一个别名,使我可以将当​​前目录添加到可执行目录。 I have this so far, but it is appending my argument into the path.. 到目前为止,我已经知道了,但这是将我的论点附加到路径中。

alias whichcd="cd $(basename "$(dirname "$1")")"

Which I run like this: 我这样运行:

$ whichcd test_bin
/home/user/test_binfinal_path

The test_binfinal_path is the appendage of the argument test_bin and the final path that which produce. test_binfinal_path是参数的附肢test_bin并且最后的路径which产生。

There are three problems: 存在三个问题:

  1. With double quotes, the $(..) runs when you create the alias, and not when you run it. 使用双引号时, $(..)创建别名时运行 ,而不是在运行别名时运行
  2. Aliases can't use positional parameters like $1 . 别名不能使用$1类的位置参数。
  3. From your description it sounds like you wanted dirname + which instead of basename + dirname 从您的描述中听起来您想要的是dirname + which而不是basename + dirname

So use a function: 所以使用一个函数:

whichcd() {
  cd "$(dirname "$(which "$1")")"
}

Now whichcd ls will take you to /bin because that's where /bin/ls is. 现在whichcd ls将带您进入/bin因为那是/bin/ls所在的位置。

I won't re-explain the things that @that other guy already explained. 我不会再解释其他人已经解释过的事情。

I have this very same but I'm using realpath in addition to what has already been said man realpath , in case which boo points to a directory where boo is actually a symlink and the real boo is somewhereElse, it cd s to somewhereElse 我有同样的想法,但是除了man realpath所说的以外,我还在使用realpath,如果which boo指向目录中boo实际上是一个符号链接,而实际的boo在某处,则cd到某处

goto () {
    cd $(dirname $(realpath $(which $1)))
}

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

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