LoginSignup
11
14

More than 5 years have passed since last update.

ShellScriptまとめ

Last updated at Posted at 2017-12-28

はじめに

シェルスクリプトで学んだことをまとめていきます.
ほとんど自分用です.

CURRENT=$(cd $(dirname $0) && pwd)の意味

これはどこでスクリプトを実行しても同じ結果になるためによく使うコマンドだそうです.
スクリプトが置かれている場所の絶対パスをCURRENTに入れます.

実行するシェルがこちら

/Users/***/Downloads/shell/hello.sh
CURRENT=$(cd $(dirname $0) && pwd)
echo $0
echo $(dirname $0)
echo $CURRENT

これを
/Users/***/Downloads

shell/hello.sh
として実行します.結果はこちら

shell/hello.sh
shell
/Users/***/Downloads/shell

まずそれぞれの意味はこんな感じです.

コマンド等 意味 
$0 スクリプトの名前
dirname hoge hogeのディレクトリ部分を返す
$(~) コマンド置換.~の部分の標準出力で $(~)を置き換える
a && b aが実行され,正常終了し戻り値が0であればbを実行
pwd カレントディレクトリを返す

流れとしては

dirname $0 で実行ファイルのあるディレクトリを標準出力に出力
↓
$( dirname $0)を出力で置き換える
↓
cd $( dirname $0)が正常に行われれば
↓
&&の右の pwd が実行される
↓
最後に$()でコマンド置換

といった感じだと思います.

$0はスクリプトの名前と書いてますが,Downloadsディレクトリで実行した場合,shell/hello.shと帰ってきてるので,実行コマンドみたいなものでしょうか?

文字列の処理

右から抽出

str=$(echo 'hogehoge' | rev | cut -c 1-2 | rev)
echo $str
# ge

反転してから1-2文字目を抽出し,反転し元に戻す感じですね.

'hoge'を含むかの判定

if [ $(echo 'asfhogeagj' | grep 'hoge') ]; then
    echo 'yes'
fi
# yes
11
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
14