bashrcに書いておくと便利なショートカット関数3つ

こういうの、設定してもだいたい忘れて使わなくなるのだけど、定着したものがいくつかあるので書いてみる。

l: ファイルにはless、ディレクトリにはlsを実行する

一つのコマンドで両方できるようにしておくと、判断の手間が省けて便利。

l() {
    # if the argument is a single file or stdin is pipe
    if [[ ($# -eq 1 && -f "$1") || (-p /dev/stdin) ]]; then
        ${PAGER:-less -R} "$@"
    else
        ls -alF --color=auto "$@"
    fi
}

ディレクトリの中身を見ながらファイルを探していくときに使う。

$ l /etc/apache2/
total 80
drwxr-xr-x   7 root root  4096 Dec  2 00:29 ./
drwxr-xr-x 110 root root  4096 Dec 12 05:33 ../
-rw-r--r--   1 root root  8346 Feb  7  2012 apache2.conf
drwxr-xr-x   2 root root  4096 Dec  2 00:29 conf.d/
-rw-r--r--   1 root root  1322 Feb  7  2012 envvars
-rw-r--r--   1 root root     0 Dec  2 00:29 httpd.conf
-rw-r--r--   1 root root 31063 Feb  7  2012 magic
drwxr-xr-x   2 root root  4096 Dec  2 00:29 mods-available/
drwxr-xr-x   2 root root  4096 Dec  2 00:29 mods-enabled/
-rw-r--r--   1 root root   750 Feb  7  2012 ports.conf
drwxr-xr-x   2 root root  4096 Dec  2 00:29 sites-available/
drwxr-xr-x   2 root root  4096 Dec  2 00:29 sites-enabled/

$ l /etc/apache2/apache2.conf
=> open the file with less

標準入力がパイプの場合はlessが走るので、コマンド文字数の省略にもなる。

$ dmesg | l
=> open dmesg's stdout with less

p: プロセスリストをgrepする

psコマンドのオプションに ww を指定すると、コマンド内容がターミナル幅で切られなくなる。 引数がないときはふつうに全プロセスを表示する。この場合は折り返しが入ると見にくいので ww はつけない。

p() {
    if [[ $# -gt 0 ]]; then
        ps auxww | grep "$@"
    else
        ps aux
    fi
}

killしたりgdbでattachするために、対象となるプロセスのPIDを調べるときに使う。

$ p apache2
root      1877  0.0  0.1  69996  3052 ?        Ss   Dec12   0:38 /usr/sbin/apache2 -k start
www-data 26914  0.0  0.0  69996  2000 ?        S    06:39   0:00 /usr/sbin/apache2 -k start
www-data 26920  0.0  0.1 359088  3172 ?        Sl   06:39   0:00 /usr/sbin/apache2 -k start
www-data 26921  0.0  0.1 424624  3176 ?        Sl   06:39   0:00 /usr/sbin/apache2 -k start
john     32652  0.0  0.0  10320   876 pts/0    S+   14:49   0:00 grep --color=auto apache2

$ sudo kill -HUP 1877
=> make apache2 to reload its configuration files

h: コマンドヒストリをgrepする

引数がないときは、直近50件のみを表示する。だいたいの場合は50件あれば十分だと思う。

h() {
    if [[ $# -gt 0 ]]; then
        history | tac | sort -k2 -u | sort | grep "$@"
    else
        history 50
    fi
}

過去にsshコマンドでログインしたホストを調べるときに使う。

$ h ssh
  128  ssh-agent screen -U
  155  ssh -A john@192.168.66.1
  164  ssh -Y -A john@192.168.44.2
  166  ssh-agent screen -U
(...)

$ !164
=> execute `ssh -Y -A john@192.168.44.2`