firstvar="PRIMARY"
secondvar="SECONDARY"
thirdvar="TERTIARY"
array=($firstvar $secondvar $thirdvar)
echo ${array[*]} //prints PRIMARY SECONDARY TERTIARY
我想在我的bash脚本中遍历这个数组,并检查数组中是否有3个元素(PRIMARY SECONDARY TERTIARY)
没有特定的顺序。是=echo "Success.
否=echo Failed
。解决这个问题的好方法是什么?
编辑:我忘了提一下,如果一个元素(例如:数组中缺少PRIMARY),它也应该打印出Primary is missing.
对于类似的数组:
array_health=($firsthealth $secondhealth $thirdhealth)
这3个变量可以是1或其他值我想检查数组中的这三个变量是否value=1,我该怎么检查呢?它们没有初始化为firsthealth=0
或firsthealth=1
。
尝试bash重新匹配
[[ ${array[@]} =~ $firstvar ]] && [[ ${array[@]} =~ $secondvar ]] && [[ ${array[@]} =~ $thirdvar ]] && echo ok || echo ko
然后像这样
for item in $firstvar $secondvar $thirdvar; {
[[ ${array[@]} =~ $item ]] && echo "$item" || echo "$item is missing"
}
初学者友好的简单循环,简单计数所有变量
后面跟着测试连接和简单的if语句
array=("$firstvar" "$secondvar" "$thirdvar")
for i in "${array[@]}"
do
echo "$i"
case "$i" in
"$firstvar")
first=$((first+1))
;;
"$secondvar")
second=$((second+1))
;;
"$thirdvar")
third=$((third+1))
;;
esac
done
if [ "$first" ] && [ "$second" ] && [ "$third" ]
then
echo "Success."
else
[ -z "$first" ] && echo "'$firstvar' missing"
[ -z "$second" ] && echo "'$secondvar' missing"
[ -z "$third" ] && echo "'$thirdvar' missing"
fi
关于你的第二个数组基本相同,引用你的vars
(虽然这是不清楚我如何想要保留标签,因为你只有数组中的值)
array_health=("$firsthealth" "$secondhealth" "$thirdhealth")
未初始化的变量可以使用-z
(如上所述)进行测试,或者使用字符串操作具有默认值
[ -z "$i" ] && echo "${i:-0}"
可以逐个遍历元素:
flag=0
for ele in "$firstvar" "$secondvar" "$thirdvar"; do
if [[ ! " ${array[@]} " =~ " ${ele} " ]]; then
echo "$ele" is missing
flag=1
fi
done
if [[ flag -eq 0 ]]; then
echo "all there"
fi
如果你的元素可能有空格,那将使上面的测试不可靠。您可以使用不同的分隔符,通过使用printf
为不太可能出现在字符串中的字符添加左右分隔符:
firstvar="PRIMARY SECONDARY"
secondvar="SECONDARY"
thirdvar="TERTIARY"
array=("$firstvar" "$thirdvar")
flag=0
printf -v tgt "|%s|" "${array[@]}" # |ele1||ele2||eleN|
for ele in "$firstvar" "$secondvar" "$thirdvar"; do
if [[ ! "$tgt" =~ "|${ele}|" ]]; then
echo "$ele" is missing
flag=1
fi
done
if [[ flag -eq 0 ]]; then
echo "all there"
fi
打印SECONDARY is missing