Random linux notes

01 01 2000

Random notes that I want to remember for using Linux. Just to not forget them.

Complex bash history

I always find the concept of history (and Ctrl-R) a bit confusing, especially when using multiple windows, multiple screens, and so on. So, I got a little script, copied from Ondřej Bojar and edited a bit.

First, install gawk (apt-get install gawk).

Then, add this to ~/.bashrc:

myHistory() {
    history 1 | awk '($2 !~ "^[mr]?cd[0-9a-z]?$") {$1="_T="strftime("%Y%m%d_%H:%M:%S_") PROCINFO["ppid"] "_PWD="  ENVIRON["PWD"] "\t"; $2=gensub("^_T=[-_0-9:]*[ \t]* *", "", 1, $2); $2=gensub("^_P=[^ \t]* *", "", 1, $2); print;}' >> ~/.complex_bash_history
export PROMPT_COMMAND="myHistory"
alias ahistory='less ~/.complex_bash_history'
alias lhistory='grep "_PWD=$PWD\s" ~/.complex_bash_history | less'

ahistory now displays all history, lhistory history in current directory; it’s possible to grep it further, since less will just behave as cat when in pipe


To .bashrc:

export PS1="\h | \t | \w\$ "

or, for manual name:

export PS1="name | \t | \w\$ "

Head and tails off-by-one

I will assume numbering of lines starts at 1, not 0.

  • head -n 4 will print everything from line 1 to line 4.
  • tail -n +4 will print everything from 4 onwards, including 4.
  • so, if you do head -n 4, you will need to do tail -n +5 if you want the rest
  • if you want first N lines for something, the next M lines for something else, and then the rest to something else, you have to do
    • cat original | head -n N | firstthing
    • cat original | head -n (N+M) | tail -n M | secondthing
    • cat original | tail -n +(N+M+1) | thirdthing