0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

zsh コマンドの色変更

0
Posted at

zshの色変え、改行、gitのブランチ表示、lsコマンドのカスタム

実行環境

OS   : MacOS
シェル: zsh

コマンドの色変え

PROMPT、入力するコマンド、結果で色を分けたいので,
PROMPT表示後から色変更しています。
また、Enterを押してコマンドを実行する直前、
プロンプトを表示する直前でhook関数を実行し色変更をしています。

~/.zshrc
# 入力コマンドの色変更終了と結果の色変更処理
function preexec_function(){
  print -Pn '%f%F{好みのRGBカラー}'
}

# 結果の色変更終了処理
function precmd_function(){
  print -Pn '%f'
}

# PROMPT表示後(入力するコマンド)の色を変更する
PROMPT="~~~好みのPROMPT~~~ "$'%F{好みのRGBカラー}'

autoload -Uz add-zsh-hook
add-zsh-hook precmd precmd_function
add-zsh-hook preexec preexec_function

下記を参考にしました

改行

PROMPTの最後に$'\n'を入れることで改行されます。
"~~~好みのPROMPT~~~"の後に$'\n'を入れましょう。

~/.zshrc
PROMPT="~~~好みのPROMPT~~~" $'\n'

gitブランチの表示

gitのブランチ名をPROMPTの最後尾に表示する処理です。
2>は、gitファイルがなかった場合の標準エラー出力を画面に表示させず、ゴミ箱に捨てる処理です。
参考資料ではブランチの状態ごとに色分けしていましたが、
簡単にブランチ名の表示のみにとどめておきます。

~/.zshrc
function git-current-branch(){
  local branch_name
  # ブランチの取得処理
  branch_name=$(git rev-parse --abbrev-ref HEAD 2> /dev/null)
  if [ -n "$branch_name" ]; then
     print -Pn "%F{好みのRGBカラー}($branch_name)%f"
  fi
}

# Enterキー入力毎に$()の中身を再計算する
setopt prompt_subst

PROMPT="~~~好みのPROMPT~~~ \$(git-current-branch)"$'\n%F{好みのRGBカラー}'

以下を参考にしました。

lsコマンドカスタム

lsをファイルの識別子付きで、
llを-alFオプション付きで表示するようにします。

~/.zshrc
alias ls='ls -F'
alias ll='ls -alF'

最終的なコード

最終的に以下のようなコードになっていると思います。
色については、%F{好みのRGBカラー}%fの{好みのRGBカラー} の中身をRGBカラーで指定すれば好みの色に変更できるので以下サイトなどで好きな色を探して変更してください。

~/.zshrc
function preexec_function(){
  print -Pn '%f%F{好みのRGBカラー}'
}

function precmd_function(){
  print -Pn '%f'
}

function git-current-branch(){
  local branch_name
  branch_name=$(git rev-parse --abbrev-ref HEAD 2> /dev/null)
  if [ -n "$branch_name" ]; then
     print -Pn "%F{好みのRGBカラー}($branch_name)%f"
  fi
}

setopt prompt_subst

PROMPT="~~~好みのPROMPT~~~ \$(git-current-branch)"$'\n%F{好みのRGBカラー}'

autoload -Uz add-zsh-hook
add-zsh-hook precmd precmd_function
add-zsh-hook preexec preexec_function


alias ls='ls -F'
alias ll='ls -alF'
0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?