bash 如何创建符号链接以在 Mac osx 上的终端中打开目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22837244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:06:28  来源:igfitidea点击:

How to create a symlink to open a directory in Terminal on Mac osx?

macosbashunixsymlink

提问by Kelly

There are certain folders I am cd'ing into all day long...for instance, "dev" which is in my Documents folder.

我整天都在整理某些文件夹……例如,我的 Documents 文件夹中的“dev”。

I had this bright idea to set up symlinks so I could simply type "dev" and Terminal would cd into that directory. This doesn't seem to work though. My two attempts are below.

我有一个很好的想法来设置符号链接,这样我就可以简单地输入“dev”,终端将 cd 进入该目录。但这似乎不起作用。我的两次尝试如下。

Anyone know how to do this or is there a better way?

任何人都知道如何做到这一点或有更好的方法吗?

ln -s /Users/kelly/Documents/Dev/ dev
ln -s 'cd /Users/kelly/Documents/Dev/' dev

$ dev
bash: dev: command not found

回答by Elmar Peise

With a symlink you can use

使用符号链接,您可以使用

ln -s your/dev/directory/ dev

but you can only use it in the directory you created it in and in the form of cd dev.

但您只能在您创建它的目录中以cd dev.

If you just want to type devat any point, use an alias:

如果您只想dev在任何时候输入,请使用别名:

alias dev="cd your/dev/direcrory/"

(this should then be in your ~/.bashrc)

(这应该在你的~/.bashrc

回答by suspectus

You could use an aliasfor dev. Add to your ${HOME}/.bashrc

您可以使用aliasfor dev。添加到您的 ${HOME}/.bashrc

 alias dev='cd /Users/kelly/Documents/Dev/' 

and bash correctly parses ~in an alias:

和 bash 正确解析~别名:

 alias dev='cd ~/Documents/Dev/' 

Using an alias eliminates the need for the symbolic link at all.

使用别名完全不需要符号链接。

回答by Stephan Kulla

You have to write cd devin your case, but it might be better for you to use bash aliases...

你必须cd dev在你的情况下写,但你最好使用bash 别名......

Write in your $HOME/.bash_aliasesfile:

在您的$HOME/.bash_aliases文件中写入:

alias dev='cd /Users/kelly/Documents/Dev/'

after opening a new terminal executing devwill give you, what you want...

打开一个新的终端执行后dev会给你你想要的......

回答by dave sines

In your $HOME/.bashrc, declare an array which maps directories to aliases.

在您的 $HOME/.bashrc 中,声明一个将目录映射到别名的数组。

declare -A __diraliasmap=(
  [dev]="/Users/kelly/Documents/Dev"
  [other]="/Users/kelly/Documents"
)

Also define a command_not_found_handle function. If defined, this function will be run by bash when a command is not found. In the function, check whether the command which failed is listed as an alias for a directory and, if so, cd to the associated directory.

还定义一个 command_not_found_handle 函数。如果已定义,则当找不到命令时,该函数将由 bash 运行。在函数中,检查失败的命令是否被列为目录的别名,如果是,则 cd 到关联的目录。

command_not_found_handle()
{
  if [[ ${__diraliasmap[]+set} = set ]]; then
    builtin cd "${__diraliasmap[]}"
  else
    false
  fi
}