Monday, November 5, 2018

Working with Your Command Line History

A trick I always forget is utilizing command line history, aside from just up-arrow.

Powershell:

This is all from "How To Geek: How to Use Your Command History in Windows PowerShell", which is a very useful site.

I spend a lot of time in Powershell, but also in PS Sessions with other systems. The up-arrow method is not always great when entering/returning from a PS Session, as it will iterate through all recent commands on your native and remote sessions. Get-History will, however, stick to the current session.
PS A:\> Clear-History
PS A:\> Get-History

  Id CommandLine
  -- -----------
 109 Clear-History

PS A:\> Enter-PSSession remotesystem
[remotesystem]: PS C:\Users\johndoe\Documents> Get-History
[remotesystem]: PS C:\Users\johndoe\Documents> cd C:\Temp\
[remotesystem]: PS C:\Temp> Get-History

  Id CommandLine
  -- -----------
   1 Get-History
   2 cd C:\Temp\

[remotesystem]: PS C:\Temp> exit
PS A:\> Get-History

  Id CommandLine
  -- -----------
 109 Clear-History
 110 Get-History
 111 Enter-PSSession remotesystem

In order to use my history (were it lengthy) I would call Invoke-History -Id n. Let's say I wanted to clear my history:
PS A:\> Invoke-History -Id 109
Clear-History
PS A:\> Get-History

  Id CommandLine
  -- -----------
 113 Clear-History

There is other great info at the linked article.

BASH:

BASH is a bit simpler, and maintains history better than Powershell. A good reference is at ss64.com, an invaluable site for the command line. Their article on BASH history is at: Connamd Line History.

The basics are easy. To see your history, use the history command. It will display the commands and their id number:
$ history
    1  history
    2  cd ~
    3  history
    4  touch somefile.txt
    5  history
    6  cd /c/temp
    7  history

To execute history item 4, simply enter !4 and return. If your history is lengthy, you could use [ctrl]+r and then start typing the command you want to find. This will begin to autocomplete the command with the appropriate text. If you want to find the command's id in your history, pipe history through grep.
$ history | grep -i some
    4  touch somefile.txt
    9  touch somefile.txt
   10  history | grep -i some

No comments: