Bash History มีความสามารถมาก การใช้ History Expansion อย่างมีประสิทธิภาพจะทำให้คุณทำงานบน Linux Command Line ได้เร็วขึ้นมาก บทความนี้อธิบาย 15 ตัวอย่างที่ใช้ฟีเจอร์ 3 ประเภท:
- Event Designators – อ้างอิงคำสั่งใน History เริ่มต้นด้วย
! - Word Designators – อ้างอิงคำเฉพาะของ History entry รวมกับ Event Designator ด้วย
: - Modifiers – ปรับเปลี่ยนผลลัพธ์จาก Event หรือ Word Designators
Event Designators
1. รันคำสั่งเฉพาะจาก History ด้วย !n
แทนที่จะพิมพ์ซ้ำ ใช้หมายเลขคำสั่งใน History:
$ !4 service sshd restart
รันคำสั่ง 2 คำสั่งก่อนหน้า:
$ !-2
รันคำสั่งก่อนหน้า (เทียบเท่า):
$ !! $ !-1
กด Ctrl+P (Emacs mode) หรือ Esc+k (Vi mode) ก็ได้
2. รันคำสั่งด้วยคำค้นหา !string และ !?string
!ps – ค้นหาคำสั่งที่ ขึ้นต้นด้วย "ps" แล้วรันทันที
$ !ps ps -ef | grep http
!?apache – ค้นหาคำสั่งที่ มีคำว่า "apache" แล้วรัน
$ !?apache /usr/local/apache2/bin/apachectl restart
3. แทนที่สตริงจากคำสั่งก่อนหน้า ^str1^str2^
$ ls /etc/cron.daily/logrotate $ ^ls^cat^ cat /etc/cron.daily/logrotate
Word Designators
4. ดึงอาร์กิวเมนต์ตัวแรก :^
$ cp /etc/passwd /backup $ ls -l !cp:^ ls -l /etc/passwd
อาร์กิวเมนต์ตัวแรกจากคำสั่งก่อนหน้า: !!:^
5. ดึงอาร์กิวเมนต์ตัวสุดท้าย :$
$ cp /etc/passwd /backup $ ls -l !cp:$ ls -l /backup
อาร์กิวเมนต์สุดท้ายจากคำสั่งก่อนหน้า: !!:$
6. ดึงอาร์กิวเมนต์ลำดับที่ n :n
$ tar cvfz /backup/home-dir-backup.tar.gz /home $ ls -l !tar:2 ls -l /backup/home-dir-backup.tar.gz
7. ดึงอาร์กิวเมนต์ทั้งหมด :*
$ cp /etc/passwd /backup $ ls -l !cp:* ls -l /etc/passwd /backup
8. อ้างอิงคำที่ค้นหาล่าสุด !%
หลังใช้ ?apache คำที่ match คือ /usr/local/apache2/bin/apachectl ใช้ !% อ้างอิงได้:
$ !% stop /usr/local/apache2/bin/apachectl stop
9. ดึงช่วงอาร์กิวเมนต์ x-y
$ tar cvf home-dir.tar john jason ramesh rita $ ls -l !tar:3-5 ls -l john jason ramesh
รูปแบบอื่นๆ:
!!:*– ทุกอาร์กิวเมนต์ของคำสั่งก่อน!!:2*– ตั้งแต่ตัวที่ 2 จนจบ!!:2-$– เหมือนข้างต้น!!:2-– ตั้งแต่ตัวที่ 2 ถึงตัวก่อนสุดท้าย
Modifiers
10. ตัด path ท้าย :h (head)
$ ls -l /very/long/path/name/file-name.txt $ ls -l !!:$:h ls -l /very/long/path/name
11. ตัด path นำหน้า :t (tail)
$ ls -l /very/long/path/name/file-name.txt $ ls -l !!:$:t ls -l file-name.txt
12. ตัดนามสกุลไฟล์ :r
$ ls -l /very/long/path/name/file-name.txt $ ls -l !!:$:r ls -l /very/long/path/name/file-name
13. แทนที่แบบ sed :s/str1/str2/
$ !!:s/ls -l/cat/
ใช้ g flag สำหรับ global replace:
$ cp /etc/password /backup/password.bak $ !!:gs/password/passwd/ cp /etc/passwd /backup/passwd.bak
14. ทำซ้ำการแทนที่ :&
หลังทำ substitution แล้ว ใช้ :& ทำซ้ำได้ทันที:
$ tar cvf password.tar /etc/password $ !!:g& tar cvf passwd.tar /etc/passwd
15. แสดงคำสั่งโดยไม่รัน :p (print)
ตรวจสอบคำสั่งก่อนรันจริง:
$ tar cvf home-dir.tar john jason ramesh rita $ tar cvfz new-file.tar !tar:3-:p tar cvfz new-file.tar john jason ramesh
ลบ :p ออกแล้วรันอีกครั้งเมื่อมั่นใจแล้ว