.bashrcでOSを確認する
2018年10月08日 月曜日 09時00分最近、.bashrc
や.vimrc
など、見直してました。
macOSで利用している.bashrc
を、Linuxでも利用したいと思ったからです。
ということで、自分用のメモ。
.bashrc
.bashrc
は、シンプルに外部ファイルを読み込むだけにしました。
gitリポジトリは、ghq
で管理しているので、こんな感じ。
. $HOME/go/src/gitlab.com/teruhirokomaki/dotfiles/.bash_bashrc.bash
. $HOME/go/src/gitlab.com/teruhirokomaki/dotfiles/.bash_alias.bash
. $HOME/go/src/gitlab.com/teruhirokomaki/dotfiles/.bash_function.bash
.bash_bashrc.bash
ファイルの一部を切り取っています。
こんな感じで記述しました。
#--------------------------------------------------
# os
#--------------------------------------------------
if [ "`uname`" == "Darwin" ]; then
ISMAC=true
elif [ "`uname`" == "Linux" ]; then
ISLINUX=true
fi
#--------------------------------------------------
# fzf
#--------------------------------------------------
if [ $ISLINUX ]; then
[ -f ~/.fzf.bash ] && source ~/.fzf.bash
fi
ファイル名についての模索
ファイル名の規則ってどんな感じなんでしょうかね?
gcpのsdkをインストールした際に.bash_profile
に追記されたのが、こちら
path.bash.inc
とcompletion.bash.inc
というファイル名なんですね。
先程の外部ファイルは.bash_bashrc.bash
としてますがbashrc.bash.inc
にしても良いかもしれない。
# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/teruhirokomaki/google-cloud-sdk/path.bash.inc' ]; then source '/Users/teruhirokomaki/google-cloud-sdk/path.bash.inc'; fi
# The next line enables shell command completion for gcloud.
if [ -f '/Users/teruhirokomaki/google-cloud-sdk/completion.bash.inc' ]; then source '/Users/teruhirokomaki/google-cloud-sdk/completion.bash.inc'; fi
ググってみた
ググってみると…
How to detect the OS from a Bash script?
uname
と$OSTYPE
のパターンがありましたが、macOSの場合の記述がシンプルなので、uname
にしました。
uname
platform='unknown'
unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]]; then
platform='linux'
elif [[ "$unamestr" == 'FreeBSD' ]]; then
platform='freebsd'
fi
$OSTYPE
if [[ "$OSTYPE" == "linux-gnu" ]]; then
# ...
elif [[ "$OSTYPE" == "darwin"* ]]; then
# Mac OSX
elif [[ "$OSTYPE" == "cygwin" ]]; then
# POSIX compatibility layer and Linux environment emulation for Windows
elif [[ "$OSTYPE" == "msys" ]]; then
# Lightweight shell and GNU utilities compiled for Windows (part of MinGW)
elif [[ "$OSTYPE" == "win32" ]]; then
# I'm not sure this can happen.
elif [[ "$OSTYPE" == "freebsd"* ]]; then
# ...
else
# Unknown.
fi
case "$OSTYPE" in
solaris*) echo "SOLARIS" ;;
darwin*) echo "OSX" ;;
linux*) echo "LINUX" ;;
bsd*) echo "BSD" ;;
msys*) echo "WINDOWS" ;;
*) echo "unknown: $OSTYPE" ;;
esac