select
select

Reputation: 2618

How to add a command to the bash history from python

I am writing a shell wrapper script (term-cheat) in python that can be used to find, collect and execute shell commands. I would love to add the executed commands to the shell history. I tried several things like the following but did not succeed.

subprocess.Popen('history -s "%s"'%command_string, shell=True, executable=os.environ['SHELL'])
os.system('fc -S "%s"'%command_string)

Upvotes: 0

Views: 1003

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295403

There is no cross-shell, universally portable option: History is an interactive facility without a close POSIX specification as to how it's implemented.

That said, there are some fixes needed to make the general approach attempted above both functional and safe:

subprocess.Popen(['bash', '-ic', 'set -o history; history -s "$1"', '_', command_string])
  • The HISTFILE variable is only set in interactive shells. Thus, you need to run bash with -i to have it set at all.
  • set -o history is similarly needed to turn history on.
  • Passing command_string out-of-band instead of substituting it into the argument following -c avoids massive security bugs (where trying to append a line to history could execute parts of it instead).

Upvotes: 3

Related Questions