使用Linux的過程中,在處理很長的並且包含復雜的語法的命令時,如果不小心犯了一點小錯誤,需要重新輸入整個命令以及參數,直到命令執行成功為止。另一種選擇是使用 fc 命令編輯並重新運行前一個命令,而無需重新輸入整個命令以及參數。
fc簡介
fc 命令是 fix command 的縮寫,是一個內建命令,它能列出、編輯、重新執行最近在交互shell中輸入的命令,你可以使用指定的編輯器編輯並運行最近輸入的命令,而不需要重新輸入整個命令。
fc命令的語法如下:
[root@ecs-centos-7 ~]# fc --h
fc: usage: fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [command]
-e 選項
使用指定的編輯器編輯,默認是 vi 編輯器, 在下面的例子中 ls /home/tt
命令在 vi 中編輯,把 ls 改成 cd,在保存退出的時候會執行 cd /home/tt
命令, 具體的結果如下:
[root@ecs-centos-7 ~]# fc -l
657 ls /home/tt
658 fc -l
[root@ecs-centos-7 ~]# fc -e vi 657
ls /home/tt
"/tmp/bash-fc-27929723442" 1L, 12C written
cd /home/tt
[root@ecs-centos-7 tt]# pwd
/home/tt
[root@ecs-centos-7 tt]#
-l 選項
列出最近的歷史命令,默認是16條
- 不帶參數,默認顯示最近的16條命令
[root@ecs-centos-7 ~]# fc -l
1 date
2 cd ~
3 fc -l
4 fc -lr
5 ls /home/tt
6 chage -l
- 顯示最近的指定行數,下面的命令顯示最近的3行
[root@ecs-centos-7 ~]# fc -l -3
4 fc -lr
5 ls /home/tt
6 chage -l
[root@ecs-centos-7 ~]#
- 指定起始行號,顯示從指定行號到末尾行的命令,下面的命令顯示行號為530到末尾行的命令
[root@ecs-centos-7 wl]# fc -l 530
530 date
531 chage -l tt
532 chage -h
533 chage -l root
534 fc -l
- 指定起始行號以及結束行號,顯示指定行號區間的命令,下面的命令顯示行號從531-534的命令
[root@ecs-centos-7 wl]# fc -l 531 534
531 chage -l tt
532 chage -h
533 chage -l root
534 fc -l
-r 選項
逆序顯示歷史命令,一般都是跟 -l 參數一起使用,下面是使用 -r 選項的例子。fc -l 選項顯示的是從1到2行的命令。執行 fc -lr 顯示的命令行數要包括前面 fc -l 的命令,所以結果會比前面多一行,執行逆序之后的行數是從3到1行, 具體的結果如下:
[root@ecs-centos-7 ~]# fc -l
1 date
2 cd ~
[root@ecs-centos-7 ~]# fc -lr
3 fc -l
2 cd ~
1 date
[root@ecs-centos-7 ~]#
-n 選項
顯示歷史命令時不顯示行號,一般都是跟-l參數一起使用, 下面的例子中沒有顯示行號
[root@ecs-centos-7 tt]# fc -l
1 date
2 chage -l tt
[root@ecs-centos-7 tt]# fc -ln
date
chage -l tt
fc -l
[root@ecs-centos-7 tt]#
-s 選項
-s [pat=rep] [command] 把 pat 命令替換成 rep 命令並執行,下面的例子把 ls /home/tt
替換成 cd /home/tt
命令,執行成功之后,當前目錄變成了 /home/tt
命令執行結果如下:
[root@ecs-centos-7 tt]# fc -l
1 date
2 ls /home/tt
[root@ecs-centos-7 tt]# fc -s cd=ls 2
ls /home/tt
[root@ecs-centos-7 tt]# pwd
/home/tt
[root@ecs-centos-7 tt]#
小技巧
一個有用的小技巧, 使用 fc -s 'pre' 可以自動運行最近一個以 'pre' 開頭的命令,輸入 fc -s
命令 可以再次執行這個命令。
[root@ecs-centos-7 ~]# fc -l
1 ls /home/tt
2 chage -l
3 date
上面是歷史命令列表,執行 fc -s 'da'
命令會執行最近一個以 'da' 開頭的命令,下面是具體的執行結果
[root@ecs-centos-7 ~]# fc -s 'da'
date
Mon Jun 29 20:26:33 CST 2020
[root@ecs-centos-7 ~]# fc -s 'l'
ls /home/tt
[root@ecs-centos-7 ~]# fc -s
ls /home/tt
從上面的結果來看,執行 fc -s 'da'
會執行最近一條以 'da' 開頭的命令,也即 date 命令。
執行 fc -s 'l'
命令會執行最近一條以 'l' 開頭的命令,也即 ls /home/tt
命令,緊接着執行 fc -s
命令,會再次執行一次 ls /home/tt
命令