Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I've always found bc kind of mysterious and intriguing. It was one of the original Unix programs. And it's a programming language unto itself. So I gladly take any chance I can find to use it.

Since bc doesn't seem to include a factorial function, I want to define one like so:

define fact(x) {
  if (x>1) {
    return (x * fact(x-1))
  }
  return (1)

}

But... I can't then reuse that, can I?

I'd want to be able to do something like

me@home$ bc <<< "1/fact(937)"
share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

Save your function definitions in a file like factorial.bc, and then run

bc factorial.bc <<< '1/fact(937)'

If you want the factorial function to always load when you run bc, I'd suggest wrapping the bc binary with a shell script or function (whether a script or function is best depends on how you want to use it).

Script (bc, to put in ~/bin)

#!/bin/sh

bc ~/factorial.bc << EOF
$@
EOF

Function (to put in shell rc file)

bc () {
    bc ~/factorial.bc << EOF
    $@
    EOF
}
share|improve this answer
    
Maybe you can call the file .bcrc? Can you put multiple definitions in the same file? –  Bernhard Jun 29 '12 at 19:47
    
Yes you can put any valid bc syntax in the file. What you call the file and where you put it is completely up to you. –  jw013 Jun 29 '12 at 20:45
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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