【问题标题】:Are there "starts with" aliases in ZSH?ZSH 中是否有“以”开头的别名?
【发布时间】:2016-11-29 01:07:18
【问题描述】:

我为我经常使用的文件夹定义了几个别名;例如

alias x="cd /home/username/git/github/user/project"

所以在终端输入x直接带我到项目文件夹。

如果字符串仅以别名开头,我认为定义一个也可以使用的别名会很好;例如如果我定义了

starts-with-alias x="cd /home/username/git/github/user/project"

打字

x/abc

会带我去:

/home/username/git/github/user/project/abc

【问题讨论】:

  • 您可能需要考虑setopt autocdcdpath+=(/home/username/git/github/user),它们应该允许project 自己切换到.../github/user 目录中的同名目录。

标签: bash alias zsh oh-my-zsh startswith


【解决方案1】:

我建议使用Static Named Directories 而不是别名,可能与选项AUTO_CD and/or CDABLE_VARS 结合使用。

静态命名目录由名称后面的~ 表示(我可以包含任何字母数字字符,_-.)。通常它们用于系统上用户的主目录,这意味着~someuser 将被用户someuser 的实际主目录替换。

zsh 中,您还可以使用以下两种方法之一定义自己的静态命名目录

  • 定义一个以/开头的值的shell参数:

    x=/home/username/git/github/user/project
    
  • 或使用带有参数-dhash 命令(与别名类似):

    hash -d x=/home/username/git/github/user/project
    

这两种方法之间的唯一区别是,第一种(显然)提供了一个 shell 参数,您可以在命名目录未扩展(例如,在带引号的字符串中)或导出为环境变量的情况下使用该参数。 使用任何一种方法,您现在都可以访问名为~x 的目录/home/username/git/github/user/project

% cd ~x
% pwd
/home/username/git/github/user/project

它也可以作为路径的第一个组件:

% cd ~x/abc
% pwd
/home/username/git/github/user/project/abc

与别名相比,它还可以与其他命令一起使用,而不仅仅是cd

% touch ~x/somefile
% echo foobar > ~x/somefile
% cat ~x/somefile
foobar

启用选项AUTO_CD 后,zsh 将自动更改为一个目录,如果它代替命令发出:

% setopt autocd
% ~x
% pwd
/home/username/git/github/user/project
% ~x/abc
% pwd
/home/username/git/github/user/project/abc

启用选项CDABLE_VARS 后,如果cd 命令(或启用AUTO_CD 的隐含cd)的参数不是目录且不以/ 开头,zsh 将尝试扩展参数,就好像它以 ~ 开头:

% setopt cdablevars
% cd x
% pwd
/home/username/git/github/user/project
% cd x/abc
% pwd
/home/username/git/github/user/project/abc

同时启用AUTO_CDCDABLE_VARS,您可以像使用cd 的别名一样使用命名目录,同时还可以直接访问子目录。

% setopt autocd cdablevars
% x
% pwd
/home/username/git/github/user/project
% x/abc
% pwd
/home/username/git/github/user/project/abc

注意:当不在cd 的上下文中使用命名目录时(通过AUTO_CD 显式或隐式)名称需要在前面加上~ 以便扩展:

% echo x/abc
x/abc
% echo ~x/abc
/home/username/git/github/user/project/abc

【讨论】:

    【解决方案2】:

    使用标准的 shell 函数,你可以做类似的事情

    x() { cd /home/username/git/github/user/project/"$1"; }
    

    x 会带你去那里,x abc 会带你去/home/username/git/github/user/project/abc

    不完全符合您的要求,但非常接近。

    免责声明:仅在bash下测试;标准语法可能会有所不同,zshone 也是如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      相关资源
      最近更新 更多