help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Kludge for handling REPL arithmetic expressions


From: Eric Pruitt
Subject: Kludge for handling REPL arithmetic expressions
Date: Mon, 2 Aug 2021 20:32:10 -0700
User-agent: Mutt/1.10.1 (2018-07-13)

I have a command setup in Bash that allows me to use "=" to do
arithmetic in an interactive session:

    ~$ = 1/42 * 9
    0.2142857142857143 (3/14)
    ~$ = log(2048, 2)
    11
    ~$ = 1/3 + 7
    7.333333333333333 (22/3)
    ~$ = x * 3
    22

It's a minor nuisance that I have to type a space after the "=" because
of the shell's grammar. It dawned on me that I could (ab)use
command_not_found_handle since I otherwise have no use for it:

    # Handler used to intercept arithmetic expressions so they can be
    # entered without having to add a space after the "=".
    #
    function command_not_found_handle()
    {
        if [[ "$1" != =* ]]; then
            printf "%s: command not found\n" "$1" >&2
            return 127
        fi

        eval "= ${1#=} ${@:2}"
    }

This works well until division comes into play:

    ~$ =2+2^7
    130
    ~$ =2/3
    bash: =2/3: No such file or directory
    (127)

Is there any way I can work around this without modifying the Bash
source code? I may regret saying this, but no kludge is too terrible. My
only requirements are that said kludge doesn't introduce any perceptible
lag to my shell and that it does NOT require that I rewrite the
expressions i.e. modify my calculator to support using another character
for division. If there's something I can configure in
libreadline/inputrc, I'm open to that, too.

Eric



reply via email to

[Prev in Thread] Current Thread [Next in Thread]