Autoexpanding aliases with readline; the story of suod

Have you ever typed suod instead of sudo? I do that quite often; maybe I am becoming typing dixleysc, who knows.

Context: Debian Gnu/Linux using the bash command line shell and bash-completion.

The problem is: execute sudo when suod is typed.

  • A trivial solution would be to put in place a shell alias:

    alias suod='sudo'
    

    it makes sense, but command line completion will not be available.

    This can be worked around by setting up the same completion function of the aliased command for the aliasing one:

    source /usr/share/bash-completion/completions/sudo
    complete -F _sudo suod
    

    this is nice, but not enough for me, it is still lacking “cross-alias” history completion in case the wrong version is typed only sometime; and history completion is the greatest thing since... you know.

  • Or, readline key bindings can be abused to implement an auto-correction functionality at the shell level. The problem is about a typo, after all.

    For that purpose this variant of key bindings will be used:

    KEYSEQ: STRING_MACRO
    

    Either the following can be put in ~/.inputrc:

    "suod": "\C-vsudo"
    

    or the bash builtin command bind can be invoked from ~/.bashrc:

    bind '"suod": "\C-vsudo"'
    

    Now every time the suod key sequence is typed in, it will be replaced automatically with sudo on the command line.

    The \C-v sequence calls the quoted-insert function which tells readline that the following character —namely s— has to be taken verbatim, this is needed to avoid that the s key is considered as the start of a macro expansion itself messing up the end result.

    This solution is good enough for me, as I get history completion.

    Maybe there could be downsides too:

    1. the expansion happens at any point in the line;
    2. there could be conflicts if many of these typo-fixing-hacks share letters one another; the possible issues could be alleviated by prefixing each character in the macro string with the sequence for quoted-insert.

SIDE NOTE

Unrelated, but while googling around I've found out how to have aliases executed in a sudo context by using this alias:

alias sudo='sudo '

Check out the Aliases section of the bash manual for the complete explanation.


CommentsSyndicate content

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
p
d
W
P
Q
M
Enter the code without spaces.