POSIX compliant arithmetic evaluation. = 10*2+3 Show Sample Output
Same functionality without using bash functions. Show Sample Output
Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?
You must be signed in to comment.
commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.
Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.
» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10
Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):
Subscribe to the feed for:
? () { let myresult="$*" ; echo $myresult; }
That would avoid changing context (launching a new process, that's what "bc" is) and would be much faster if you are using the calculations in some loop or whatever. To ensure that, I made a quick test: I defined "?" as my function, and "x" as your function, and measured their times for a simple compound calculation:time ( for a in {0..999}; do ? "($a*$a-$a)/($a+$a+1)" > /dev/null ; done )
real 0m0.767s user 0m0.624s sys 0m0.144stime ( for a in {0..999}; do x "($a*$a-$a)/($a+$a+1)" > /dev/null ; done )
real 0m6.777s user 0m1.544s sys 0m4.548s Of course, it might be that you would miss some functionality for advanced calculations using the internal shell syntax instead of bc. But then again, bc (-l or not) has its limitations: you can't use it for non-integer exponentials, that is:echo "2^(1/3)" | bc -l
Runtime warning (func=(main), adr=9): non-zero scale in exponent I would recommend installing the "concalc" package if you need better mathematical evaluations in shell commands:echo "2^(1/3)" | concalc
1.25992104989487316?
as a function name. Thanks for the example for that, even if I don't use the calculator function! :)<<< "x=1; y=2; p=3*x+2*y; p" bc -l
echo $[ 1*2 + 3 ]
5bc <<< 10*2+3
# bash arithmetic
function ? { echo $[$*] }
# awk arithmetic (floating point result)
function calc(){ awk "BEGIN{ print $* }" ;}
bc -l<<<3/7
echo $[2*(3+5)]
16 awk for floating point and powersfunction ? { awk "BEGIN{ print $* }" ;}
? '((2+1)/7)^3.5'
0.0515325 concalc for full scientific functions:concalc<<<'sin(32^(1/3))'
-0.0332033464121159848 bc for high precision:bc -l<<<3/7
.42857142857142857142 gp for number theory: gp -qf 2.6040699049291378729513930560926568818 E574964gp -qf
2.6040699049291378729513930560926568818 E574964gp -qf<<<'123456! + 0.'
2.6040699049291378729513930560926568818 E574964