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: Greg Wooledge
Subject: Re: Kludge for handling REPL arithmetic expressions
Date: Wed, 4 Aug 2021 10:27:29 -0400

I'll also point out this... this thing here, because it seems to be
relevant to part of the original goal.

Some of you may have heard of "magic aliases".  It's not an official
term, but it's the name by which I was introduced to this thing.  The
idea is that you abuse the nature of shell aliases (which delay the
parsing of arguments) to create a pseudo-function that isn't subject
to the standard rules of syntax.

The alias is created as a wrapper around a function.  The function
receives the input that you type, *exactly* as you typed it, by
extracting it from the shell's history.  It doesn't receive arguments
in the normal sense.

So, here goes:

unicorn:~$ alias m='math_it # '
unicorn:~$ math_it() {
> local exp
> read -r _ _ exp < <(history 1)
> printf '%s\n' "$exp" | bc -l
> }
unicorn:~$ m 3/6
.50000000000000000000
unicorn:~$ m 3 * 5
15
unicorn:~$ m l(2048)
7.62461898615939840358

The standard parsing rules don't apply here.  The * is not expanded
as a glob, and the parentheses don't trigger a subshell or a syntax
error.

Now, for the next trick: using '=' as the alias name.  We can't do it
in the normal way:

unicorn:~$ alias =='math_it # '
bash: alias: ==math_it # : not found
unicorn:~$ alias '='='echo hi'
bash: alias: ==echo hi: not found

But we can use the side door:

unicorn:~$ BASH_ALIASES[=]='math_it # '
unicorn:~$ = 2+4
6

There is no sane way to make '=2+4' work with this approach, though.
You need a separator between the alias name and the rest of the
command, so the parser knows that it has an alias to be expanded.
But if you can live with having to type a space after the = sign, it's
not too terrible.

This is yet another path that I wouldn't pursue personally, but it's more
to my liking than the command_not_found_handle approach.  Slightly.



reply via email to

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