bash函式應用之:判斷函式是否存在

weixin_33670713發表於2018-11-01

bash函式應用之:判斷函式是否存在

如何判斷一個函式是否存在,如果存在則呼叫它。

#!/bin/bash

function myfun_foo1() {
    echo "in myfun_foo: $1"
}

if [ "$(type -t myfun_foo1)" == function ]; then
  echo "function myfun_foo is defined"
  myfun_foo1 "AAA"
else
  echo "function myfun_foo is NOT defined"
fi

if [ "$(type -t myfun_foo2)" == function ]; then
  echo "function myfun_foo is defined"
  myfun_foo2 "AAA"
else
  echo "function myfun_foo is NOT defined"
fi

這個執行結果:

function myfun_foo is defined
in myfun_foo: AAA
function myfun_foo is NOT defined

例子2:使用變數函式名

#!/bin/bash

function myfun_foo1() {
    echo "in myfun_foo: $1"
}

typeset SUFFIX=foo1
if [ "$(type -t myfun_${SUFFIX})" == function ]; then
  echo "function myfun_foo is defined"
  myfun_${SUFFIX} "AAA"
else
  echo "function myfun_foo is NOT defined"
fi

typeset SUFFIX=foo2
if [ "$(type -t myfun_${SUFFIX})" == function ]; then
  echo "function myfun_foo is defined"
  myfun_${SUFFIX} "AAA"
else
  echo "function myfun_foo is NOT defined"
fi

執行結果:

function myfun_foo is defined
in myfun_foo: AAA
function myfun_foo is NOT defined

相關文章