このエントリーをはてなブックマークに追加


実行するシェルスクリプト名を取得する

シェルスクリプトを作成したとき、スクリプト自身のファイル名(スクリプト名)を取得したくなる場合がありますよね。
例えば、引数が足りない場合などにusageのメッセージを出す場合などがありますよね。 以下、引数に誤りがある場合にusageメッセージを表示するスクリプトを例に説明します。


basenameでスクリプト名を取得する

basenameコマンドによりファイル名を取得することができます。
シェルスクリプトでは$0に実行したスクリプト名が代入されています。

#!/bin/bash
echo $0

上記のシェルスクリプトを動かしてみます。
以下のように指定されたスクリプト名が$0に代入されているのがわかります。

$ chmod +x test.sh 
$ ./test.sh 
./test.sh
$ /home/sakura/test.sh
/home/sakura/test.sh

basenameを利用したサンプルシェルスクリプト(script_name_1.sh)

以下にbasenameを利用したサンプルシェルスクリプトを紹介します。

#!/bin/bash

function usage {
  echo Usage: `basename $0` "<message>"
  exit 1
}

if [ $# != 1 ]; then
  usage
else
  echo ARGV: $1
fi

exit 0

script_name_1.shの動作結果

動作例を2つ記します。
1つ目は引数を渡さず実行した状態です。
Usageが表示されます。 $ ./script_name_1.sh Usage: script_name_1.sh <message>

2つ目は引数(hello world)を渡し実行した例です。
引数で渡した文字列が表示されています。

$ ./script_name_1.sh "hello world" ARGV: hello world

${parameter##word}を利用したサンプルシェルスクリプト(script_name_2.sh)

basenameのかわりに${parameter##word}を利用した例です。
basename と ${parameter##word} は同じ動作となります。
${parameter##word}はbashで利用できます。

#!/bin/bash

function usage {
  echo Usage: ${0##*/} "<message>"
  exit 1
}

if [ $# != 1 ]; then
  usage
else
  echo ARGV: $1
fi

exit 0

man bash の抜粋

参考までに${0##*/} の動作について、manから抜粋しました。

${parameter##word}
             The word is expanded to produce a pattern just  as  in  pathname
             expansion.  If the pattern matches the beginning of the value of
             parameter, then the result of  the  expansion  is  the  expanded
             value of parameter with the shortest matching pattern (the ``#''
             case) or the longest matching pattern (the ``##'' case) deleted.
             If parameter is @ or *, the pattern removal operation is applied
             to each positional parameter in turn, and the expansion  is  the
             resultant  list.   If parameter is an array variable subscripted
             with @ or *, the pattern removal operation is  applied  to  each
             member  of the array in turn, and the expansion is the resultant
             list.

関連資料


添付ファイル: filetest.sh 586件 [詳細] filescript_name_2.sh 443件 [詳細] filescript_name_1.sh 495件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2015-03-20 (金) 22:26:56