击:测试多个变量的相互平等? [英] Bash: test mutual equality of multiple variables?
问题描述
什么是测试如果几个变量是正确的方式人人平等?
What is the right way to test if several variables are all equal?
if [[ $var1 = $var2 = $var3 ]] # syntax error
是否有必要写类似下面?
Is it necessary to write something like the following?
if [[ $var1 = $var2 && $var1 = $var3 && $var2 = $var3 ]] # cumbersome
if [[ $var1 = $var2 && $var2 = $var3 && $var3 = $var4 ]] # somewhat better
不幸的是,另有优秀高级bash脚本编程指南和其他在线资源,我能找到唐'吨提供这样的例子。
Unfortunately, the otherwise excellent Advanced Bash Scripting Guide and other online sources I could find don't provide such an example.
我的具体动机是,以测试几个目录都具有相同数量的文件使用 LS -1 $目录|厕所-l
计数的文件。
My particular motivation is to test if several directories all have the same number of files, using ls -1 $dir | wc -l
to count files.
注意
结果
VAR1等都是例子变数。我在寻找任意变量名的解决方案,而不仅仅是那些有predictable数字的结局。
Note
"var1" etc. are example variables. I'm looking for a solution for arbitrary variable names, not just those with a predictable numeric ending.
更新
结果
我已经接受RICHO的回答,因为这是最普遍的。不过,我实际使用凯尔的,因为它是最简单的,我的投入有保证,避免警告。
Update
I've accepted Richo's answer, as it is the most general. However, I'm actually using Kyle's because it's the simplest and my inputs are guaranteed to avoid the caveat.
感谢您的建议,每个人。
Thanks for the suggestions, everyone.
推荐答案
如果你想测试项目任意数量的平等(我们称他们为$ item1-5,但他们可能是一个数组
if you want to test equality of an arbitrary number of items (let's call them $item1-5, but they could be an array
st=0
for i in $item2 $item3 $item4 $item5; do
[ "$item1" = "$i" ]
st=$(( $? + st ))
done
if [ $st -eq 0 ]; then
echo "They were all the same"
fi
这篇关于击:测试多个变量的相互平等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!