bash 根据参数中的特定单词执行函数

bash execute functions based on certain word in arguments

我有以下bash脚本包含多个函数

#!/usr/bin/bash

#checks if the arguments is directory and extract the domain name from it
if [[ -d "" ]]; then
    domain=$(echo "" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
    WORKING_DIR=""
else
    domain=""
    echo "it is domain name"
fi

example_fun1(){
    ping -c 4 $domain
}

example_fun2(){
    nslookup $domain
}

for x in "$@" ;do
    example_fun1 $x
    example_fun2 $x
done

和运行如下

./script.sh ./pathtofolder/example.com/ ./pathtofolder/test.com/

./script.sh example.com test.com

并且可能工作,但我需要添加更多功能,即检查基于参数的某些单词是否像 fun1 它只会执行函数 example_fun1

期望执行

./script.sh fun1 ./pathtofolder/example.com/ ./pathtofolder/test.com/

./script.sh fun1 example.com test.com

谢谢

将第一个参数分配给一个变量,然后在调用函数时使用它。

func="example_"
shift

for x in "$@"; do
    "$func" "$x"
done

并且您的函数需要使用它们的参数,而不是在主脚本中设置的变量:

example_fun1(){
    ping -c 4 ""
}

example_fun2(){
    nslookup ""
}

尝试以下方法

#!/usr/bin/bash

function=""
if [[ $( echo  | grep fun1 ) ]]
then
     function="example_fun1"
     shift
elif [[ $( echo  | grep fun2 ) ]]
then
     function="example_fun2"
     shift
fi

#checks if the arguments is directory and extract the domain name from it

example_fun1(){
    ping -c 4 $domain
}

example_fun2(){
    nslookup $domain
}

if [[ "$function" != "" ]]
then
        for input in "$@"; do
            if [[ -d "" ]]; then
                domain=$(echo "" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
                WORKING_DIR=""
            else
                domain=""
                echo "it is domain name"
            fi
            "$function"
            shift
        done
else
        for input in "$@"; do
            if [[ -d "" ]]; then
                domain=$(echo "" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
                WORKING_DIR=""
            else
                domain=""
                echo "it is domain name"
            fi
             example_fun1
             example_fun2
             shift
        done
fi

这样你就可以通过fun1并只执行 fun1 或者,如果您不传递其中任何一个,例如,它们都将被执行