-3

This code print all the bash history but i have to print last 20 bash history.How can i do that?

import fpdf

pdf = fpdf.FPDF(format='letter')
pdf.add_page()
pdf.set_font("Arial", size=14)

for history in open('.bash_history'):
    pdf.write(8,history)

pdf.output("bash.pdf")
Shubham Gupta
  • 43
  • 1
  • 4
  • 2
    This might help: [Get last n lines of a file with Python, similar to tail](https://stackoverflow.com/q/136168/3776858) or [Copy the last three lines of a text file in python?](https://stackoverflow.com/q/15647467/3776858) – Cyrus Dec 17 '18 at 08:03
  • 1
    Note that .bash_history is only the history last time it was saved. There may be newer commands in an ongoing session, so this utility will probably only be useful in a startup script. You would emit the bash command `history` for the latest history. – Gem Taylor Dec 17 '18 at 11:16

1 Answers1

1

The .bash_history file contains the entire history in order. You could simply load the file in a python list and then splice the list as per your requirements.

For Example, the following snippet will print the last 20 statements from the history file:

print list(open('{PATH}/.bash_history'))[-20:]

pixie999
  • 468
  • 5
  • 11