willemdh
willemdh

Reputation: 856

Validate arguments and set value if empty with bash function

I have a function that enables me to check for unset variables:

ValidateArgs () {
for Var in "$@" ; do
    echo "Validating argument $Var with value \"${!Var}\"."
    if [ -z "${!Var}" ] ; then
        echo "Argument \"$Var\" is required. Please define $Var."
        read -rp "Enter $Var: " Var
        echo -e "\n"
    fi
done
}

I'd like to enhance this function so it is able to set a value for the arguments passed after reading it with read -rp.

I tried several combinations, is it possible to do this and if so what would be the ebst way?

The function is called like this:

ValidateArgs Action HostName

if Action and HostName are unset after going through the ValidateArgs function a value is asked and should be set. I would prefer to use the function in the main script.

Upvotes: 0

Views: 254

Answers (1)

Karan Shah
Karan Shah

Reputation: 1324

Try creating a script and run it inside the original shell using source like this:

ValidateArgs () {
for Var in "$@" ; do
    echo "Validating argument $Var with value \"${!Var}\"."
    if [ -z "${!Var}" ] ; then
        echo "Argument \"$Var\" is required. Please define $Var."
        printf "Enter $Var: "
        read value
        export $Var=$value
    fi
done
}

ValidateArgs $@

One you do this, you can run the script like:

source ./test.sh myvar
Validating argument myvar with value "".
Argument "myvar" is required. Please define myvar.
Enter myvar: myvalue

echo $myvar
myvalue

Upvotes: 1

Related Questions