Home > other >  bash execute functions based on certain word in arguments
bash execute functions based on certain word in arguments

Time:02-10

i have the following bash script contains multiple functions

#!/usr/bin/bash

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

and run as following

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

Or

./script.sh example.com test.com

and working probably BUT i need to add more feature which is check if certain word based in arguments like fun1 it will execute function example_fun1 only

desired execution

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

OR

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

Thanks

CodePudding user response:

Try the following

#!/usr/bin/bash

function=""
if [[ $( echo $1 | grep fun1 ) ]]
then
     function="example_fun1"
     shift
elif [[ $( echo $1 | 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 "$1" ]]; then
                domain=$(echo "$1" | grep -iEo '[[:alnum:]-] \.[a-z] ')
                WORKING_DIR="$1"
            else
                domain="$1"
                echo "it is domain name"
            fi
            "$function"
            shift
        done
else
        for input in "$@"; do
            if [[ -d "$1" ]]; then
                domain=$(echo "$1" | grep -iEo '[[:alnum:]-] \.[a-z] ')
                WORKING_DIR="$1"
            else
                domain="$1"
                echo "it is domain name"
            fi
             example_fun1
             example_fun2
             shift
        done
fi

This way you can pass fun1 and execute only fun1 Or if you don't pass any of these for example both of them will be executed

CodePudding user response:

Assign the first parameter to a variable, then use that when calling the function.

func="example_$1"
shift

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

And your functions need to use their parameters, not a variable that's set in the main script:

example_fun1(){
    ping -c 4 "$1"
}

example_fun2(){
    nslookup "$1"
}
  • Related