Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

switon

macrumors 6502a
Original poster
Sep 10, 2012
636
1
Hi all,

Topher Kessler just posted a nice review of the bash "history" commands on reviews.cnet.com.

The link is:
http://reviews.cnet.com/8301-13727_7-57561873-263/using-and-managing-the-terminal-history-in-os-x/

I thought I might add just a couple of my favorite uses of bash history to his fine article for those interested in using bash.

Kessler explains how to retrieve an earlier bash command and rerun it. I'd like to point out that the command can also be edited before rerunning it. For instance, the following commands:

Code:
ls -al /Users/username/Notes/Mac
!!:s/Mac/PC/

where the first command lists the directory /Users/username/Notes/Mac
while the second command replaces the Mac with PC to execute the directory listing on /Users/username/Notes/PC instead. The normal bash pattern matching commands using #, ##, %, %%, ^, ?, *, etc. also work.

Another favorite bash history command is: (assuming you have more than 525 lines in your bash history file)

Code:
...
ssh -p52221 username1@machinename.domainname
...
history | grep -i ssh
...
!525:p

where the "history | grep" command prints out all ssh commands you have used. Say the command 525 is the ssh command listed. Then the "!525: p" [the : and p should not have a space between them, but when the space is removed, the blog code converts it into an emoticon] command will recall the "ssh -p52221 username1@machinename.domainname" line and print it. You can then use the "uparrow" to recall this printed ssh command to the current command line, and then interactively edit it using the left- and right-arrow keys, delete, cntrl-A, cntrl-K, etc. When you hit return, your newly edited ssh command will be executed. Note you could also edit the previous ssh command line from above history "in situ", so to speak, with:

Code:
!525:s/username1/username2/

which would ssh to username2's account instead of username1's account on the machinename.domainname computer.

I find the ability to quickly edit previously executed bash commands to be a valuable time-saver.

Regards,
Switon
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.