LoginSignup
55
53

More than 5 years have passed since last update.

chpwd内のlsでファイル数が多い場合に省略表示する

Last updated at Posted at 2012-12-26

zshではchpwd関数を定義することで、ディレクトリ移動後に任意のコマンドを実行することができます。

zshユーザの多くは、chpwd内でlsを実行するよう設定しているのではないでしょうか。

しかし、移動先のディレクトリに大量のファイルやディレクトリが存在していると、lsの結果で画面が一杯になってしまいます。
移動するたびにこれでは正直困ります。

そこでファイル数が多い場合には省略表示するchpwdの設定を紹介します。

どんな感じになるかというと…

screenshot

いかがでしょう、これでうっかりファイル数の多いディレクトリに移動してしまっても大丈夫です。

コードは以下

chpwd() {
    ls_abbrev
}
ls_abbrev() {
    if [[ ! -r $PWD ]]; then
        return
    fi
    # -a : Do not ignore entries starting with ..
    # -C : Force multi-column output.
    # -F : Append indicator (one of */=>@|) to entries.
    local cmd_ls='ls'
    local -a opt_ls
    opt_ls=('-aCF' '--color=always')
    case "${OSTYPE}" in
        freebsd*|darwin*)
            if type gls > /dev/null 2>&1; then
                cmd_ls='gls'
            else
                # -G : Enable colorized output.
                opt_ls=('-aCFG')
            fi
            ;;
    esac

    local ls_result
    ls_result=$(CLICOLOR_FORCE=1 COLUMNS=$COLUMNS command $cmd_ls ${opt_ls[@]} | sed $'/^\e\[[0-9;]*m$/d')

    local ls_lines=$(echo "$ls_result" | wc -l | tr -d ' ')

    if [ $ls_lines -gt 10 ]; then
        echo "$ls_result" | head -n 5
        echo '...'
        echo "$ls_result" | tail -n 5
        echo "$(command ls -1 -A | wc -l | tr -d ' ') files exist"
    else
        echo "$ls_result"
    fi
}

Macの場合は、glsが使用可能ならそちらを優先して使用します。

lsのオプションや省略表示を行う行数のしきい値などはお好みに応じて変更して下さい。
上記コードでは10行より多い場合は、前後5行づつ表示するようになっています。

gistにもあげました。
chpwd for zsh - gist

55
53
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
55
53