1

My .bash_aliases file is populated with single-letter aliases (such as o for octave-cli and r for sudo reboot.

For a while I've been wanting to implement BASH's built-in calculator to do quick calculations, mostly integer multiplication and exponentiation. Sometimes I'll run echo $((expression)) in the terminal, however it would be great to make a shorthand for that, so that I could simply write

c expression

into a terminal. It would be ideal to declaire something like

alias c="echo $(($@))"

into the .bash_aliases file, however that does not work (it prints a 0 as well as the unsolved expression). In what ways do I have to modify the command above to make it possible for 'expression' c expression to be passed onto echo $(($@)). I've had the idea of including a function in the .bash_aliases file, however do not know how to correctly direct the argument.

1

1 Answer 1

2

Aliases cannot take positional parameters. For that you'd need a function:

$ c(){ echo "$(($@))";  }
$ c 2+2
4

This is not anything new nor dodges the question about aliases. Same has been covered here , here , here, and dozen other posts.

While it is possible to "simulate" the behavior for aliases in some cases with xargs, the approach is error prone, difficult to maintain, and doesn't work consistently. In general, if you don't want to use a function for some reason but want to have a command-line utility to perform calculations, use suggestions given in Any command line calculator for Ubuntu?. A dedicated tool such as those suggested can do more than just bash arithmetic expansion, which is another benefit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.