bash中的后缀别名

bri*_*out 4 unix linux bash zsh

后缀别名是我考虑切换到ZSH但我想坚持使用bash的唯一原因.那么在bash中可能有类似后缀别名的东西吗?

对于那些不知道后缀别名是什么的人,在ZSH中有以下内容

$ alias -s cpp=vi
$ filename.cpp
Run Code Online (Sandbox Code Playgroud)

将运行vifilename.cpp作为第一个参数.

请注意,像xdg-open或gnome-open这样的东西是不够的.我希望bash在输入文件名时执行命令.

完成对我来说非常重要.因此,如果输入文件名的开头,那么当按下TAB键时,如果完成文件名的其余部分将会很好.

sar*_*old 12

您可以使用新command_not_found_handle()功能构建一个.获得zsh后缀别名的完整功能比这里的简单示例需要更多的工作; 但我的简单例子可能足以满足您的需求:

$ command_not_found_handle() { if [[ $1 =~ .*.cpp ]]; then vi $1 ; elif [[ $1 =~ .*.java ]]; then cat $1 ; fi ; }
$ splice.cpp  # started vi on splice.cpp
$ Year.java
import java.util.Scanner;

class Year {
    public static void main(String[] args) {
        Scanner yearenter = new Scanner(System.in); 
        System.out.println("Enter year ");
        int year = yearenter.nextInt();     
        System.out.print("Year " + year + " is ..");
        if (year % 400!=0 || year % 4 != 0 && year % 100==0)
            System.out.println(" not a leapyear"); 
        else
            System.out.println(" a leapyear"); 

    }    
} 
$ 
Run Code Online (Sandbox Code Playgroud)

这里的功能扩展到足够清晰:

command_not_found_handle()
{
    if [[ $1 =~ .*.cpp ]]
    then
        vi "$1"
    elif [[ $1 =~ .*.java ]]
    then
        cat "$1"
    fi
}
Run Code Online (Sandbox Code Playgroud)

根据您的需要扩展它 - 每个=~都是正则表达式匹配,所以随意使用您想要的任何正则表达式.

请注意,这与command-not-foundDebian和Ubuntu软件包冲突,因此您可能需要卸载或以其他方式取消限制此软件包以获得可靠的结果.(只需确保包含系统范围的文件,您自己~/.bashrc~/.bash_profile文件中定义了此功能,它应该正常工作.)/etc/bash*