0

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.

1
  • 1
    Technically, you aren't checking for unset variables; you are checking for variables that lack a non-empty value. Read up on the -v operator and ${var:?msg} parameter expansions. Commented Feb 13, 2017 at 13:10

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I would prefer to use the function in the main script if possible, to avoid dependencies. But interesting suggestion, tx.
I was able to use the export method in the main script. Answer accepted. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.