【问题标题】:Validate arguments and set value if empty with bash function如果为空,则使用 bash 函数验证参数并设置值
【发布时间】:2017-02-13 11:43:13
【问题描述】:

我有一个函数可以让我检查未设置的变量:

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
}

我想增强此功能,以便它能够为使用read -rp 读取后传递的参数设置一个值。

我尝试了几种组合,是否可以这样做?如果可以,最好的方法是什么?

函数是这样调用的:

ValidateArgs Action HostName

如果在通过 ValidateArgs 函数后未设置 Action 和 HostName ,则会询问并应设置一个值。我更喜欢在主脚本中使用该函数。

【问题讨论】:

  • 从技术上讲,您不是在检查未设置的变量;您正在检查缺少非空值的变量。阅读-v 运算符和${var:?msg} 参数扩展。

标签: bash function validation arguments


【解决方案1】:

尝试创建一个脚本并使用 source 在原始 shell 中运行它,如下所示:

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 $@

如果你这样做,你可以像这样运行脚本:

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

echo $myvar
myvalue

【讨论】:

  • 如果可能的话,我宁愿在主脚本中使用该函数,以避免依赖。但有趣的建议,tx。
  • 我能够在主脚本中使用导出方法。回答接受。干杯
猜你喜欢
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 2022-06-19
相关资源
最近更新 更多