Help us understand the problem. What is going on with this article?

【Zsh】aliasのaliasが書きたい

More than 1 year has passed since last update.

動機

定番のalias。

case "$OSTYPE" in
  freebsd*|darwin*)
    alias ls='ls -F -G -w';;
  linux*)
    alias ls='ls -F --color=auto';;
esac

共通しているオプションがあるので、下のように書きたい。

alias ls='ls -F'

case "$OSTYPE" in
  freebsd*|darwin*)
    alias ls='ls -G -w';;
  linux*)
    alias ls='ls --color=auto';;
esac

しかしこれでは単にaliasを上書きしているだけなので、最初のaliasは跡形もなく消えます。

$ alias ls='ls -F'
$ alias ls='ls --color=auto'
$ alias ls
ls='ls --color=auto'

案1. 変数を使う

ls=ls
ls="$ls -F"
ls="$ls --color=auto"
alias ls="$ls"
unset ls

愚直です。何をしているかは分かりやすいです。

案2. evalを使う

alias ls=ls
eval alias $(alias ls)"' -F'"
eval alias $(alias ls)"' --color'"

ちょっと黒魔術的です。

関数化

_alias() { echo alias $(alias $1 || echo "'$1=$1'")"'${2:gs/\'/"'\\''"/}'"; }

eval $(_alias ls ' -F')
eval $(_alias ls ' --color')

aliasが存在しない場合の処理やらなんやら追加したら長くなったので関数化しました。
黒魔術度が増しました。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away