想象一下我们有一个这样的数组:
declare -a array=( "one" "two" "three" "four" "five" )
for i in "${all[@]}"; do
echo "$i"
done
我们可以像这样提供来自用户的输入:
read -p "Enter a number: " number
我需要一些东西来检查用户输入是否与该数组的元素之一匹配。如果没有,这应该运行:
echo "Try again: "
应重复此过程,直到用户输入与数组元素之一匹配。
您不需要遍历数组来检查值是否属于它。此外,在这种情况下,我将使用函数的递归调用而不是另一个循环。正如我正确理解的那样,您正在寻找这样的东西:
#!/bin/bash
array=( "one" "two" "three" "four" "five" )
function get_input() {
read -p "${1}: " number
if [[ " ${array[*]} " == *" ${number} "* ]]
then
echo 'true';
else
get_input 'Try again' # a recursive call of the function
fi
}
get_input 'Enter a number' # the initial call of the function
使用[[
测试命令,我们==
在一个字符串(左侧)和一个正则表达式(右侧)之间进行精确匹配。
该表达式" ${array[*]} "
将我们的数组扩展为一个字符串,由两个空格包围,因此每个元素(即使是第一个和最后一个)都将被空格包围 - try echo '^'" ${array[*]} "'$'
。
正则表达式*" ${number} "*
将匹配由变量的值组成的任何$number
字符串,由空格包围,由任何其他字符包围*
。
我们可以通过其他一些工具来执行这样的测试grep
(使用抑制的 stdout -q
,并搜索精确匹配\<...\>
)。这是一个有趣的版本:
#!/bin/bash
array=( "one" "two" "three" "four" "five" )
function get_input() {
read -p "${1}: " nm
echo "${array[*]}" | grep -q "\<${nm}\>" && echo 'true' || get_input 'Try again'
}
get_input "Enter a number"
如果我们想调用数组中每个元素对应的编号,而不是插入像''one''或''two''这样的词,我们该怎么做?例如:输入数字:2
#!/bin/bash
array=( "one" "two" "three" "four" "five" )
# Get the lenght of the array
array_lenght="${#array[*]}"
function get_input() {
read -p "${1}: " number
# Test whether the variable $number has a value &and&
# test whether as integer this value is less or equal to the $array_lenght
if [[ ! -z ${number} ]] && (( number <= array_lenght && number > 0 ))
then
# Outpit the value of the cerain array element
# Note the first array element has number 0
echo "${array[$(( number - 1 ))]}"
else
get_input 'Try again'
fi
}
get_input 'Enter an integer number'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句