11

bash has a handy file .bash_history in which it saves the history of commands and on the next execution of bash the history is populated with saved commands.

Is it possible to save bc command history to a file in the same way and then load it on startup so that bc history is preserved?

I tried reading GNU bc manual and it mentions readline and libedit. From ldd /usr/bin/bc I see mine uses readline and readline has write_history and read_history functions. Is this functionality implemented in bc or to do it I'll need to patch bc?

15

If you aren't happy with the command line editing features that are built into a program, you can run it through rlwrap. This is a wrapper around a command line processor (a REPL) that lets you edit each line before it's sent. Rlwrap uses the readline library and saves history separately for each command.

Running rlwrap bc won't do anything for you because rlwrap detects that your bc wants to do its own command line editing, so rlwrap turns itself off. Since you do want rlwrap's command line editing features and not the underlying command's, run

rlwrap -a bc

The command history will be saved in ~/.bc_history.

The main downside of relying on rlwrap rather than using the program's own readline integration is that rlwrap can't do any context-sensitive completion. For example, the python toplevel completes known variables and fields, but rlwrap python cannot do that. Since bc doesn't appear to have any custom completion, rlwrap -a bc doesn't lose functionality over bc.

| improve this answer | |
  • Brilliant, I was also looking for something similar, and it look like rlwrap is the solution. – adhrar_nmatrous Sep 16 at 17:30
  • 1
    This is just amazing and works real good. I didn't know about rlwrap - really amazing utility that I will use from now on. The if hash rlwrap 2>/dev/null; then bc() { rlwrap -a bc "$@"; }; fi landed in my .bashrc. – KamilCuk Sep 16 at 19:27
4

This method with tee works for me. It saves the whole dialogue.

$ rm -i bc.log; tee -a bc.log | bc | tee -a bc.log
rm: remove regular file 'bc.log'? y
3*4
12
9*16
144
^C
$ cat bc.log    
3*4
12
9*16
144
$ 

You could also have separate log files for the input and output of bc.

The next example shows how only the input is saved, and appended between sessions.

$ rm bc.log  # only when you want to clear the log file

$ tee -a bc.log | bc
7+5-2
10
37*27
999
225/3
75
^C
$ cat bc.log
7+5-2
37*27
225/3
$ tee -a bc.log | bc
2^10
1024
^C
$ cat bc.log
7+5-2
37*27
225/3
2^10
$ 
| improve this answer | |

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.