help-bash
[Top][All Lists]
Advanced

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

Re: Kludge for handling REPL arithmetic expressions


From: David
Subject: Re: Kludge for handling REPL arithmetic expressions
Date: Tue, 3 Aug 2021 15:34:49 +1000

On Tue, 3 Aug 2021 at 13:32, Eric Pruitt <eric.pruitt@gmail.com> wrote:

> 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 imagine it's readily achievable.
In the function, I would detect three cases:
  either "$1" == '=' or "$1" == =* or neither.
Then for both the matches, use some method to remove the "=",
ie discard the whole $1 or discard just its first character, as required.
Then use arithmetic context $(( ... )) to evaluate the rest of the
arguments, then printf the result.



reply via email to

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