シェルスクリプトで関数名を動的に作って呼び出すというものを
書いていたんですが、できあがった関数名が存在しなかった場合、
どう対応したらいいのかわからなかったので調べてみました。
typeビルトイン関数
ビルトイン関数 typeを使うことで指定した名前が関数であるかどうか
判断できます。
% : zshの場合 % test10 () { echo 'hello' } % type test10 test10 is a shell function % unfunction test10 % type test10 test10 not found % : bashの場合 % test10 () { > echo 'hello' > } % type test10 test10 は関数です test10 () { echo 'hello' } % unset -f test10 % type test10 bash: type: test10: 見つかりません
シェル関数と定義されていたら, それを教えてくれます。
実際使うときはメッセージは不要なので $?を確認するとよいかと思います。
実例としては以下のような感じになるかと思います。
#!/bin/sh test_1 () { echo 'test1' } test_2 () { echo 'test2' } index=$1 testname=test_$index if type $testname 1>/dev/null 2>/dev/null then $testname else echo "Error undefined function '$testname'" fi
実行結果
% ./function_tested.sh 1 test1 % ./function_tested.sh 2 test2 % ./function_tested.sh 3 Error undefined function 'test_3'