Reputation: 125
I have an Ansible playbook which collects some informations and finally write into a file something like this :
VAR_A=14.12.103
VAR_B=14.12.103
VAR_C=14.12.103
VAR_D=14.12.103
VAR_E=14.12.103
VAR_F=14.12.103
VAR_G=14.12.103
VAR_H=14.12.103
Then, I use a shell script to compare theses values to be sure that every vars are each identical to the other.
What is the best way to compare theses vars ? Actually I do :
if [ "$VAR_A" = "$VAR_B" ] && [ "$VAR_B" = "$VAR_C" ] && [ "$VAR_C" = "$VAR_D" ] && [ "$VAR_D" = "$VAR_E" ] && [ "$VAR_E" = "$VAR_F" ] && [ "$VAR_F" = "$VAR_G" ] && [ "$VAR_G" = "$VAR_H" ]; then
echo "OK"
exit 0
else
echo "KO"
exit 2
fi
but i think that's not the best way..
Does somebody gots another solution ?
Thanks
Upvotes: 1
Views: 48
Reputation: 141493
finally write into a file something like this :
I would:
[[ "$(sed 's/^VAR_[A-H]=//' file | uniq | wc -l)" -eq 1 ]]
That could be significantly slower, but more readable. An awk
solution could be significantly faster.
I think in awk, you could, untested:
if awk -F'=' 'NR==1{l=$2} NR!=1{if ($2 != l) exit 1}' file; then
Upvotes: 1
Reputation: 785611
Using awk you may use:
if awk -F= 'NR == 1 {v = $2} $2 != v {exit 1}' file; then
echo "OK"
exit 0
else
echo "KO"
exit 2
fi
Upvotes: 1
Reputation: 302
Depends on what you define "best"? Are you looking for runtime? or clarity?
because you can use a loop to compare VAR_A
to all others, and if any comparison is false return KO
else OK
.
I can't think of a way to make it faster in bash but will edit if anything comes to mind.
Upvotes: 1