#navi(../)

* 実行するシェルスクリプト名を取得する [#a645d4c3]
#contents

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

#htmlinsertpcsp(linux_ads_top.html,linux-sp.html)

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

#ref(test.sh)
 #!/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) [#yb948be2]
以下にbasenameを利用したサンプルシェルスクリプトを紹介します。

#ref(script_name_1.sh)

 #!/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の動作結果 [#gd2a7258]
動作例を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) [#z9678105]
basenameのかわりに${parameter##word}を利用した例です。~
basename と ${parameter##word} は同じ動作となります。~
${parameter##word}はbashで利用できます。

#ref(script_name_2.sh)
 #!/bin/bash
 
 function usage {
   echo Usage: ${0##*/} "<message>"
   exit 1
 }
 
 if [ $# != 1 ]; then
   usage
 else
   echo ARGV: $1
 fi
 
 exit 0

** man bash の抜粋 [#ac88b431]
参考までに''${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.

*関連資料 [#qd8578a2]
- [[逆引きUNIXコマンド/ディレクトリ文字列を削除しファイル名のみを抽出する方法]]
#br
#htmlinsertpcsp(linux_ads_btm.html,linux-sp.html)

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS