Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2912

よく使うけどよくググるシェルスクリプト小技集

$
0
0

はじめに

「よく使うけどよくググる」
つまり、忘れがちだったり、コピペすることが多いものをまとめています。

目次

小技集

シェバン

#!/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 --helpfi

コマンドが存在しない場合

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 --helpfi

Fedora/RedHat系の場合

if[-e /etc/fedora-release -o-e /etc/redhat-release ];then
  yum --helpfi

Yes or No で処理分岐

read-p'yes or no? [y/N]: ' yn
if["$yn"!='y'];then
  echo'no...'exit
fi

まとめ

ひとまず思いついたものをあげてみました。
その他、「よく使うけどよくググる」がありましたら、まとめていきたいと思います。

GitHub: @yukiarrr
Twitter: @yukiarrr


Viewing all articles
Browse latest Browse all 2912

Trending Articles