简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM