bash中的后缀别名

时间:2012-01-30 00:43:49

标签: linux unix zsh bash

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

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

$ alias -s cpp=vi
$ filename.cpp

将以vi作为第一个参数运行filename.cpp

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

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

1 个答案:

答案 0 :(得分: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"); 

    }    
} 
$ 

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

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

根据您的需要扩展它 - 每个=~ is a regular expression match,所以请随意使用您想要的任何正则表达式。

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