Suffix aliases in bash

Suffix aliases are the only reason I'm going to switch to ZSH, but I want to stick with bash. So, is it possible to have something like suffix aliases in bash?

For those who don’t know what the suffix alias is, in ZSH

$ alias -s cpp=vi $ filename.cpp 

will start vi with filename.cpp as the first argument.

Please note that something like xdg-open or gnome-open is not enough. I want bash to execute a command when entering a file name.

Completion is very important to me. Therefore, if the beginning of the file name is typed, it would be nice if the rest of the file name was filled when the TAB key was pressed.

+4
source share
1 answer

You can create one using the new command_not_found_handle() function. Getting the full potential of the zsh suffix alias will require more work than my simple example; but my simple example may be sufficient for your needs:

 $ 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"); } } $ 

Here the function is extensible enough to be legible:

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

Extend it as you see fit - each =~ matches a regular expression , so feel free to use any regular expressions you want.

Please note that this conflicts with the command-not-found packages of Debian and Ubuntu, so you may need to remove or otherwise disable this package to get reliable results. (Just make sure this function is defined in your own ~/.bashrc or ~/.bash_profile file after including system-wide /etc/bash* files, and it should just work.)

+11
source

Source: https://habr.com/ru/post/1393668/


All Articles