除了琳瑯滿目的常見指令,Linux 還藏著許多冷門卻好用的工具。以下精選 10 個,或許能為你的日常操作帶來驚喜。
名字前個 p,一看就知道與程序有關,又是 grep,正是程序相關的 grep。它主要用來列舉程序 ID:
$ pgrep -u hchen
22441
22444
相當於:
ps -ef | egrep '^hchen' | awk '{print $2}'
以樹狀方式列出程序,一目了然:
[hchen@RHELSVR5 ~]$ pstree
init-+-acpid
|-auditd-+-python
| `-{auditd}
|-automount---4*[{automount}]
|-httpd---10*[httpd]
|-sshd---sshd---sshd---bash---pstree
|-syslogd
`-xinetd
做高精度數學運算,例如開平方根。以下是用 bc 寫的腳本(檔名 sqrt):
#!/bin/bash
if [ $# -ne 1 ]
then
echo 'Usage: sqrt number'
exit 1
else
echo -e "sqrt($1)\nquit\n" | bc -q -i
fi
使用方式:
[hchen@RHELSVR5]$ ./sqrt 36
6
[hchen@RHELSVR5]$ ./sqrt 2.0000
1.4142
想把一個大檔切成小檔,就靠它:
[hchen@RHELSVR5 applebak]# split -b 50m largefile.tar.gz LF_
[hchen@RHELSVR5]# ls -l LF_*
-rw-r--r-- 1 hchen hchen 52428800 05-10 18:34 LF_aa
-rw-r--r-- 1 hchen hchen 52428800 05-10 18:34 LF_ab
...
合併只需:
[hchen@RHELSVR5]# cat LF_* >largefile.tar.gz
與 cat 很像,但會印出行號:
[hchen@RHELSVR5 include]# nl stdio.h | head -n 10
1 /* Define ISO C stdio on top of C++ iostreams.
2 Copyright (C) 1991,1994-2004,2005,2006 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
熟悉 Unix 的人都知道,這是建立有名管道的系統呼叫或命令。平時用豎線「|」串接命令是使用無名管道,而 mkfifo 用的是有名管道。先建立:
[hchen@RHELSVR5 ~]# mkfifo /tmp/hchenpipe
[hchen@RHELSVR5 ~]# ls -l /tmp
prw-rw-r-- 1 hchen hchen 0 05-10 18:58 hchenpipe
在一個 shell 執行(不會返回,除非有人讀走資訊):
[hchen@RHELSVR5 ~]# ls -al > /tmp/hchenpipe
在另一個視窗讀取(會使上一命令返回):
[hchen@RHELSVR5 ~]# head /tmp/hchenpipe
可知道一個可執行檔用了哪些動態連結庫:
[hchen@RHELSVR5 ~]# ldd /usr/bin/java
linux-gate.so.1 => (0x00cd9000)
libgij.so.7rh => /usr/lib/libgij.so.7rh (0x00ed3000)
libpthread.so.0 => /lib/i686/nosegneg/libpthread.so.0 (0x00110000)
libc.so.6 => /lib/i686/nosegneg/libc.so.6 (0x0022f000)
可把 man 頁轉成純文字檔:
# PAGER=cat
# man less | col -b > less.txt
可檢查一個 XML 文件的所有 tag 是否正常:
[hchen@RHELSVR5 ~]# curl 'https://cocre.com/?feed=rss2' > cocre.xml
[hchen@RHELSVR5 ~]# xmlwf cocre.xml
[hchen@RHELSVR5 ~]# xmlwf cocre.xml
cocre.xml:13:23: mismatched tag
可列出已開啟的檔案:
[root@RHELSVR5 ~]# lsof | grep TCP
httpd 548 apache 4u IPv6 14300967 TCP *:http (LISTEN)
sshd 1764 root 3u IPv6 4993 TCP *:ssh (LISTEN)
mysqld 10202 mysql 10u IPv4 73819697 TCP *:mysql (LISTEN)
vsftpd 11095 root 3u IPv4 152157957 TCP *:ftp (LISTEN)