Shell History - BruceDai003/tech_blog GitHub Wiki

本文介绍如何使用shell的历史命令,来更高效的完成一些命令。

Run the last command as root

sudo !!

这里一个!是一个even designators,用来引用过去的一条历史命令,一般是相对于当前命令而言的。后面可以跟很多参数,第二个!就是一个参数,表示最近的一次命令。 比如

$ adduser sam
-bash: /usr/sbin/adduser: Permission denied

$ sudo !!
sudo adduser sam
$ id sam

可以看到,输入sudo !!后实际执行的命令sudo adduser sam也会显示出来。 那么,!!显然就是重复上一条命令,其实也相当于!-1, 即相对于当前的前一条命令。!-N表示相对于当前的前N跳命令。如果不加负号,是表示绝对的第N条命令,感觉这个不常用,一般相当于当前的前1,2条吧。

Repeat the Last Command That Started with a given String

很简单,!<string>即可。如果是引用最近的包含某一个String的命令,是!?<string>[?],其中最后一个?当是后面是换行符的时候可以省略。

Reuse the word from the previous command

使用上一个命令的第二个单词(第一个参数)

$ !^

举例:

$ host www.google.com 8.8.8.8
Using domain server:
Name: 8.8.8.8
Address: 8.8.8.8#53
Aliases:
www.google.com has address 173.194.46.83
www.google.com has address 173.194.46.81
www.google.com has address 173.194.46.84
www.google.com has address 173.194.46.82
www.google.com has address 173.194.46.80
www.google.com has IPv6 address 2607:f8b0:4009:805::1013
$ ping -c1 !^
ping -c1 www.google.com
PING www.google.com (173.194.46.80) 56(84) bytes of data.

使用上一条命令的最后一个单词(最后一个参数):

$ !$

举例:

$ unzip tpsreport.zip
Archive: tpsreport.zip
inflating: cover-sheet.doc
$ rm !$
rm tpsreport.zip

使用上一条命令的第N个单词(从0开始算)

$ <event_designator>:<number>
$ !!:N
$ !w:3 #(以w开头的最近一条命令的第3个单词(从0算)

Repeat the Previous Command While Substituting a String

$ ^<string1>^<string2>^ (替换第一个)
$ ^<string1>^<string2>^:& (替换所有出现的string1)
$ ^<string1>^<string2>^:G
$ !!:gs/string1/string2

Reference a Word of the Current Command and Reuse it

!#:N

显然!#引用当前的命令行。 举个例子:

$ mv Working-with-Files.pdf Chapter-18-!#:1
mv Working-with-Files.pdf Chapter-18-Working-with-Files.pdf

Clear your history

history -c
⚠️ **GitHub.com Fallback** ⚠️