はじめに
「よく使うけどよくググる」
つまり、忘れがちだったり、コピペすることが多いものをまとめています。
目次
- シェバン
- スクリプトのディレクトリに移動
- スクリプトの親ディレクトリの絶対パスを取得
- case文での条件分岐
- 文字列が空文字かチェック
- ファイルが存在するかチェック
- コマンドが存在するかチェック
- OSの判別
- Linuxディストリビューションの判別
- Yes or No で処理分岐
小技集
シェバン
#!/bin/bash
エラーが出た際にスクリプトを停止したい場合は、
#!/bin/bash -e
スクリプトのディレクトリに移動
cd $(dirname $0)
スクリプトの親ディレクトリの絶対パスを取得
hoge=$(dirname $(cd $(dirname $0); pwd))
$(dirname $(dirname $0))
だと、$0
が./hoge.sh
のような相対パスだった場合に挙動がおかしくなるので注意。
case文での条件分岐
case "$hoge" in
'a' ) echo 'a' ;;
'b' ) echo 'b' ;;
* ) exit 1 ;;
esac
文字列が空文字かチェック
空文字ではない場合
if [ -n "$hoge" ]; then
echo "$hoge"
fi
空文字の場合
if [ -z "$hoge" ]; then
echo 'empty'
fi
ファイルが存在するかチェック
ファイルが存在する場合
if [ -e $hoge ]; then
echo "$hoge"
fi
ファイルが存在しない場合
if [ ! -e $hoge ]; then
echo 'not exists'
fi
コマンドが存在するかチェック
コマンドが存在する場合
if type hoge > /dev/null 2>&1; then
hoge --help
fi
コマンドが存在しない場合
if ! type hoge > /dev/null 2>&1; then
echo 'not exists'
fi
OSの判別
Macの場合
if [ "$(uname)" = 'Darwin' ]; then
echo 'macos'
fi
Linuxの場合
if [ "$(uname -s | cut -c -5)" = 'Linux' ]; then
echo 'linux'
fi
Windowsの場合
if [ "$(uname -s | cut -c -5)" = 'MINGW' -o "$(uname -s | cut -c -7)" = 'MSYS_NT' ]; then
echo 'windows'
fi
Linuxディストリビューションの判別
Ubuntu/Debian系の場合
if [ -e /etc/debian_version -o -e /etc/debian_release ]; then
apt --help
fi
Fedora/RedHat系の場合
if [ -e /etc/fedora-release -o -e /etc/redhat-release ]; then
yum --help
fi
Yes or No で処理分岐
read -p 'yes or no? [y/N]: ' yn
if [ "$yn" != 'y' ]; then
echo 'no...'
exit
fi
まとめ
ひとまず思いついたものをあげてみました。
その他、「よく使うけどよくググる」がありましたら、まとめていきたいと思います。