1. 程式人生 > 實用技巧 >10個很實用Linux命令,千萬不要錯過

10個很實用Linux命令,千萬不要錯過

下面介紹的命令都是不常見但又是很實用的命令,學會了它們,工作上更得心應手

1. !!

回想下自己身上是否發生過這樣一種情況,當鍵入一行很長的命令敲擊回車之後才發現命令開頭忘記加 sudo 了,這時候你只需要鍵入 sudo !!,命令列自動把 !!替換成你上一條執行的命令

[tt@ecs-centos-7 ~]$ yum install cowsay
Loaded plugins: fastestmirror
You need to be root to perform this command.
[tt@ecs-centos-7 ~]$ sudo !!
sudo yum install cowsay

2. cd -

使用過Linux系統的人都知道 cd ..命令 是返回上一級目錄,但是很少人知道 cd - 命令作用是返上一次cd到的目錄

[root@ecs-centos-7 ~]# pwd
/root
[root@ecs-centos-7 ~]# cd /home/tt
[root@ecs-centos-7 tt]# pwd
/home/tt
[root@ecs-centos-7 tt]# cd -
/root
[root@ecs-centos-7 ~]# pwd
/root
[root@ecs-centos-7 ~]# cd -
/home/tt
[root@ecs-centos-7 tt]# pwd
/home/tt

上面的例子中,首先當前目錄是:/root 執行 cd /home/tt之後目錄變為/home/tt,然後執行 cd - 目錄又變成了/root,再次執行cd -,當前目錄又回到了/hom/tt

3. cd

你可能知道 ~ 表示Home目錄,但是很少人知道的一個小竅門: 如果你鍵入 cd 命令,依然能回到Home目錄

[root@ecs-centos-7 ~]# pwd
/root
[root@ecs-centos-7 ~]# cd /home/tt
[root@ecs-centos-7 tt]# pwd
/home/tt
[root@ecs-centos-7 tt]# cd
[root@ecs-centos-7 ~]# pwd
/root
[root@ecs-centos-7 ~]# 

4. 搜尋

你可以通過鍵盤上的上下鍵搜尋已經鍵入過的命令,可能你需要連續按15次向上箭頭的按鍵才能找到曾經輸入過的ls 命令。現在使用反向搜尋可以很輕鬆的實現: 按一下Ctrl + R 鍵後開始輸入命令,反向搜尋功能會從最近歷史命令中查詢和輸入最匹配的命令

[tt@ecs-centos-7 ~]$ ls -lh
total 0
-rw-rw-r-- 1 tt tt 0 Jul  2 00:40 a.txt
[tt@ecs-centos-7 ~]$ date
Thu Jul  2 00:41:00 CST 2020
(reverse-i-search)`l': ls -lh

total 0
-rw-rw-r-- 1 tt tt 0 Jul  2 00:40 a.txt
[tt@ecs-centos-7 ~]$ 

5. 重用引數

另一個小竅門是 !$ 它會被替換成前面一個命令的引數。這是很實用的,例如,當你新建立了一個目錄並且想進入這個目錄:

[tt@ecs-centos-7 ~]$ mkdir temp
[tt@ecs-centos-7 ~]$ cd !$
cd temp
[tt@ecs-centos-7 temp]$ pwd
/home/tt/temp
[tt@ecs-centos-7 temp]$

6. 拷貝和貼上

你可能已經發現了 Ctrl + CCtrl + V,這兩個組合在終端上是預留給正在執行的程序用的,可以用Ctrl + Shift + CCtrl + Shift + V來替代 Ctrl + CCtrl + V的功能。

7. 讓你的程式後臺執行

在終端執行應用程式時,應用程式會隨著終端的關閉而退出。使用 nohup命令可以實現終端退出,應用程式依然執行著,nohup 是 "no hang up"的縮寫。
例如:使用scp命令從本地傳輸大檔案到遠端伺服器上,假如突然關掉終端的話,如何保證傳輸不會中斷呢?下面的命令會解決這個問題。

nohup scp big_file user@host:~/big_file

nohup 會建立一個nohup.out檔案記錄命令的輸出

8. 自動確認

在編寫shell指令碼自動執行任務時,有時需要人工輸入 yes ,命令才會往下執行。在命令前加上 yes | 就會跳過人工輸入的步驟,下面的命令會自動輸入 yes

yes | yum install lrzsz  

如果想自動輸入 no ,則在命令前加上no |,下面的命令會自動輸入 no

9. 粉碎檔案

如果你比較注重隱私的話,那這個命令很適合你。rm命令常用來刪除檔案,刪除之後可以通過特殊的軟體提取出已經刪除的檔案資料。想要徹底刪除,可以試下下面的命令

shred -zvu filename

10. vim為檔案設定密碼

  • 如果檔案處於vim編輯狀態,切換到命令模式,輸入:X(注意:這裡是大寫的X) 輸入密碼,再次確認密碼之後儲存退出
  • 如果檔案沒有處於編輯狀態,使用 vim +X filename 也可以為檔案設定密碼

下面是為檔案 a.txt 設定密碼

[root@ecs-centos-7 ~]# vim a.txt
:X
Warning: Using a weak encryption method; see :help 'cm'                 
Enter encryption key: ***
Enter same key again: ***

設定密碼之後,無論是通過cat還是vim都無法直接檢視或者編輯 a.txt

[root@ecs-centos-7 ~]# cat a.txt 
VimCrypt~01!q,oot@ecs-centos-7 ~]#
[root@ecs-centos-7 ~]# vim a.txt
Need encryption key for "a.txt"
Warning: Using a weak encryption method; see :help 'cm'
Enter encryption key:

從上面可以看出,使用 cat a.txt命令看到的是一串亂碼,通過vim a.txt 編輯檔案,需要先輸入密碼