'How to create dynamic IF condition
I have been writing a script which will run in while loop infinite times
If all condition are met then only the script will break and execute another command
My code :
while true
do
# Note : below field will execute some command and generate value
field1=`some command which gives status`
field2=`some command which gives status`
field3=`some command which gives status`
field4=`some command which gives status`
if [ "$field1" == "A" ] && [ "$field2" == "A" ] && [ "$field3" == "A" ] && [ "$field4" == "A" ]
then
break
else
echo "Conditions are not met !!!"
fi
done
echo "Another command execution started ... "
The issue here is the number of fields might vary
Need to make my script generic and incase I have 10 fields also it should frame a
if condition dynamically and start executing until all fields becomes equal to A and break for executing another command
Solution 1:[1]
Something like this? But this only works with single line result
A="A"
output="something to start"
until [ -z "$(echo $output | grep -v $A)" ]
do
output=$(cat <<EOF
`cat A` # First command
`cat B` # Second command
EOF
)
echo "Waiting for condition"
sleep 1
done
you could try to
echo "A" > A
echo "B" > B
Stop condition
echo "A" > B
Solution 2:[2]
Using an array for your fields lets you loop over them, and putting it in a function lets you use return to end execution even if inside multiple nested loops:
poll() {
while true; do
declare -a fields=( )
# Note : below field will execute some command and generate value
fields[1]=`some command which gives status`
fields[2]=`some command which gives status`
fields[3]=`some command which gives status`
fields[4]=`some command which gives status`
any_bad=0
for field_idx in "${!fields[@]}"; do
field_val=${fields[$field_idx]}
if [[ $field_val != "A" ]]; then
echo "Conditions not met (field $field_idx is not $field_val, not A)" >&2
any_bad=1
break
fi
done
(( any_bad == 0 )) && return
done
}
poll
Solution 3:[3]
So just check for any line other than A.
res=$(
some command which gives status
some command which gives status
some command which gives status
some command which gives status
)
if <<<"$res" grep -xFqv A; then
echo "Conditions is not met !!!"
fi
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | KamilCuk |
