“如何多次使用一个验证函数”;bash centos”的英文缩写;

“如何多次使用一个验证函数”;bash centos”的英文缩写;,bash,function,shell,Bash,Function,Shell,我只想多次使用一个验证函数。我试着做一个如下的验证函数。我如何修复代码并多次使用像这样的验证函数 #!/bin/bash digit='^[[:digit:]]+$'; function numberValidate { if [[ $1 =~ $digit ]]; then echo "$1 is number. Correct"; else echo “Enter only numbers”; n

我只想多次使用一个验证函数。我试着做一个如下的验证函数。我如何修复代码并多次使用像这样的验证函数

#!/bin/bash
digit='^[[:digit:]]+$';
function numberValidate {
    if [[ $1 =~ $digit ]];
       then
          echo "$1 is number. Correct";
       else
          echo “Enter only numbers”;
          numberValidate
    fi
}
printf “Enter the number 1 ”; read n1;
numberValidate $n1
printf “Enter the  number 2”; read n2;
numberValidate $n2

谢谢。

当循环可以执行以下操作时,不要使用递归:

inputNumber () {
    local digit='^[[:digit:]]+$'
    read $n
    until [[ ${!n} =~ $digit ]]; do
        echo "Enter only numbers"
        read $n
    done
}
printf "Enter the number 1 "; inputNumber n1
printf "Enter the number 2 "; inputNumber n2
前面的步骤将所有输入移动到验证函数中,并利用函数中设置的变量默认为全局变量这一事实。
inputNumber
的参数是要设置的变量的名称

inputNumber () {
    local digit='^[[:digit:]]+$'
    outputvar=$1
    shift
    if [[ $# = 0 ]]; then
       read -p "Please enter a number for ${outputvar} "
    else
       read -p "$* " n
    fi
    until [[ "${n}" =~ $digit ]]; do
        read -p "Enter only numbers " n
    done
    printf -v "${outputvar}" '%s' "$n"
}

inputNumber n1 "Enter the number 1"
inputNumber n2 "Enter the number 2"
inputNumber n3
echo "n1=${n1} n2=${n2} n3=${n3}"
评论中的问题:如何重用这些? 当您喜欢这样的函数时,您可以将它们收集到文件中,并将它们放在专用目录中。可能选择${HOME}/shlib作为文件夹,并创建像iofunctions、datefunctions、dbfunctions和webfunctions(或io.sh、date.sh、db.sh和web.sh)这样的文件。 接下来,您可以
source
带点的文件:

$ head -2 ${HOME}/shlib/iofunctions
# This file should be included with ". path/iofunctions"
function inputnumber {

$ cat ${HOME}/bin/roger.sh
#!/bin/bash
# Some settings
shlibpath=/home/roger/shlib
# Include utilities
. "${shlibpath}"/iofunctions
# Let's rock
inputNumber rockcount How many rocks
# call an imaginary function that only accepts y and n
inputyn letsdoit Are you sure
您可以将函数(或函数文件的源代码)放在.profile/.bashrc中,但当您想在crontab中启动脚本时,就会出现问题(而且您会习惯这些函数,忘记inputNumber不是标准的bash函数)。
另一个问题是如何引用与脚本文件处于同一级别的另一个目录(不是固定路径)。当您使用路径(如
bin/roger.sh
)启动脚本时,包含
。/shlib/iofunctions
将失败。一个有很多答案的好问题,我不知道哪一个是最好的:





出现问题时递归调用
numberValidate
可能是错误的。函数不会传递任何值,但它需要一个值,并且不会提示输入值。你需要更仔细地思考如何让它发挥作用。您需要能够(再次)从函数中提示输入一个数字,并且您需要能够以某种方式从函数中获取值……这里使用智能引号显然是错误的。您的代码是从Microsoft平台复制和粘贴的吗?也就是说,这个问题没有实际问题——这只是一堆代码,表明您已经知道如何多次调用函数(标题似乎表明您正在询问)。如果你问为什么代码以给定的方式失败,请描述失败模式以及你打算它做什么;请参阅。在这种情况下没有区别,但我建议
printf“%s”输入数字1“
。我尝试了您的代码,但它对我无效。我必须做以下更改:在n上没有间接寻址(
readn
${n}=~$digit
),并添加行
printf-v$1'%s'$n
。我在你的解决方案中遗漏了什么?好问题;我不确定。我需要在
读取$n
之前添加一行。该行为
n=“$1”
。以改进此代码。此解决方案在一个文件(bash)中工作。如果你想在另一个文件中工作,我必须复制这个函数。“每个文件的此函数(bash)”。问题是我如何在一个文件中有许多函数,而从另一个文件中只调用此文件来工作。