Teruhiro Komaki

日々の生活や、プログラミング、Claris FileMakerに関する情報をメモしておく雑記帳です。

.bashrcでOSを確認する

2018-10-08

最近、.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.inccompletion.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

参考にしました