Linux 命令行小技巧 – !嘆號(hào)的用處
history 的基礎(chǔ)
??HISTSIZE?
?? 變量值設(shè)置保存在歷史列表中的命令數(shù)。默認(rèn)情況下,該值為 500。這些先前發(fā)出的命令(稱為歷史列表)存儲(chǔ)在歷史文件中。它的默認(rèn)位置是??~/.bash_history?
??,這個(gè)位置存儲(chǔ)在shell變量??HISTFILE?
??中。本文中使用??!?
?命令將 bash 歷史記錄列表中的命令引入到輸入中。此功能使使用者可以輕松地快速重復(fù)命令、替換文本、操作參數(shù)和修復(fù)先前命令中的拼寫錯(cuò)誤。
命令重復(fù)實(shí)例
以下是可以使用??!?
? 執(zhí)行操作的一些示例。-重復(fù)匹配字符串開頭的最后一個(gè)命令??!?
?后跟與要運(yùn)行的命令匹配的第一個(gè)字符(或者字符串)將重復(fù)該命令的實(shí)例:
[root@localhost ~]# ls /root/
anaconda-ks.cfg centos2ol.sh employee.json list_users new.txt wsbkuplog.txt
[root@localhost ~]# !l
ls /root/
anaconda-ks.cfg centos2ol.sh employee.json list_users new.txt wsbkuplog.txt
[root@localhost ~]# !ls
ls /root/
anaconda-ks.cfg centos2ol.sh employee.json list_users new.txt wsbkuplog.txt
-重復(fù)匹配字符串中任意位置的最后一個(gè)命令??!??
?格式與上述相同,但李世明令不必是命令的開頭:
[root@localhost ~]# cat employee.json
[{"name": "John Brooks","id": "003"},{"name": "Randy Park","id": "053"},{"name": "Todd Gray","id": "009"}]
[root@localhost ~]# !?employee
cat employee.json
[{"name": "John Brooks","id": "003"},{"name": "Randy Park","id": "053"},{"name": "Todd Gray","id": "009"}]
[root@localhost ~]# !?json
cat employee.json
[{"name": "John Brooks","id": "003"},{"name": "Randy Park","id": "053"},{"name": "Todd Gray","id": "009"}]
-重復(fù)歷史記錄中的第 n 個(gè)命令重復(fù) bash 歷史記錄中的第 n 個(gè)命令:
[root@localhost ~]# !772
-重復(fù)最后一條命令如果有一個(gè)我一直使用的命令,那就是??!!?
??。重復(fù)歷史列表中的最后一個(gè)命令,其行為與 ??!-1?
? 相同:
[root@localhost ~]# cat employee.json
[{"name": "John Brooks","id": "003"},{"name": "Randy Park","id": "053"},{"name": "Todd Gray","id": "009"}]
[root@localhost ~]# !!
cat employee.json
[{"name": "John Brooks","id": "003"},{"name": "Randy Park","id": "053"},{"name": "Todd Gray","id": "009"}]
[root@localhost ~]# !-1
cat employee.json
[{"name": "John Brooks","id": "003"},{"name": "Randy Park","id": "053"},{"name": "Todd Gray","id": "009"}]
[root@localhost ~]#
如果上一條命令忘記添加??sudo?
??來執(zhí)行,可以結(jié)合??!!?
?來使用。還可以后面結(jié)合管道符使用。
$ yum update
Loaded plugins: priorities, update-motd, upgrade-helper
You need to be root to perform this command.
$ sudo !!
sudo yum update
Loaded plugins: priorities, update-motd, upgrade-helper
$ ls
dir dir1 dir2 file file1 file2 hello.txt
$ !! | grep file
ls | grep file
file
file1
file2
-重復(fù)并替換字符串我經(jīng)常發(fā)輸入較長(zhǎng)的命令,然后用不同的參數(shù)重新輸入?;蛘撸倚枰匦掳l(fā)出一個(gè)命令,因?yàn)槲抑暗拿钪杏幸粋€(gè)錯(cuò)字。字符串替換讓我無需重新輸入整個(gè)長(zhǎng)命令即可完成此操作。下面是語法:
!!:s^oldstring^newstring
命令中的??^?
?是分隔符,用后面的newstring字符串替換前面的oldstring字符串。
[root@localhost ~]# ll /etc/httpd/conf.d
total 16
-rw-r--r-- 1 root root 2926 Nov 4 2020 autoindex.conf
-rw-r--r-- 1 root root 400 Nov 4 2020 README
-rw-r--r-- 1 root root 1252 Nov 4 2020 userdir.conf
-rw-r--r-- 1 root root 764 Nov 4 2020 welcome.conf
[root@localhost ~]# !!:s^conf.d^conf
ll /etc/httpd/conf
total 28
-rw-r--r-- 1 root root 11899 Nov 4 2020 httpd.conf
-rw-r--r-- 1 root root 13064 Nov 4 2020 magic
[root@localhost ~]#
總 結(jié)
這些是每個(gè)系統(tǒng)管理員都應(yīng)該熟悉的命令。這些命令可以節(jié)省大量時(shí)間。