[英]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
. 我想增强此功能,以便它能够为使用
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. 如果在通过ValidateArgs函数后未设置Action和HostName,则将询问并应设置一个值。 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: 尝试创建脚本并使用如下所示的
source
在原始外壳中运行脚本:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.