5

My end goal is capture the previous command executed in the terminal. Since ~/.bash_history doesn't include commands from the current terminal session, I can't simply read that file.

From another thread, I found this script:

from subprocess import Popen, PIPE, STDOUT
shell_command = 'bash -i -c "history -r; history"'
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, 
    stderr=STDOUT)

output = event.communicate()

That's pretty close to what I'm looking for, but it also will not include the history from the current terminal session since it's started as a subprocess. Is there any way to execute a similar command in the current shell?

2

1 Answer 1

6

why don't you read the file directly. ~/.bash_history

for history in open('/home/user/.bash_history'):
    print(history, end='')
Sign up to request clarification or add additional context in comments.

3 Comments

Because my end goal is capture the previous command executed in the terminal, and ~/.bash_history doesn't include commands from the current terminal session.
I should make that more clear in the original question. Thanks for the advice, though.
That's the default behaviour but you could write a function to make the shell append the previous command to the history file before prompting for a new command.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.