シェルスクリプトを作成したとき、スクリプト自身のファイル名(スクリプト名)を取得したくなる場合がありますよね。
例えば、引数が足りない場合などにusageのメッセージを出す場合などがありますよね。
以下、引数に誤りがある場合にusageメッセージを表示するスクリプトを例に説明します。
basenameコマンドによりファイル名を取得することができます。
シェルスクリプトでは$0に実行したスクリプト名が代入されています。
#!/bin/bash echo $0
上記のシェルスクリプトを動かしてみます。
以下のように指定されたスクリプト名が$0に代入されているのがわかります。
$ chmod +x test.sh $ ./test.sh ./test.sh $ /home/sakura/test.sh /home/sakura/test.sh
以下にbasenameを利用したサンプルシェルスクリプトを紹介します。
#!/bin/bash function usage { echo Usage: `basename $0` "<message>" exit 1 } if [ $# != 1 ]; then usage else echo ARGV: $1 fi exit 0
動作例を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
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
参考までに${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.