SLS SLS - 2 months ago 11
Bash Question

how to return true in bash if all conditions success ?

is there any specific way to check if the condition true on for loop and return true.
ex -

`

check_all_1_to_8_eq()
{
for i in {1..8}; do
if [ a == $i ];then
return 0
else
return 1
fi
done
}`


i want to check if all 1 to 8 are return true then end of the function return true , if on of the if condition return false , then function return false. Please let me know how to solve these type of script.

Answer

Continue looping if the condition succeeds, and return outside the loop. If the condition fails, return at that point:

check_all_1_to_8_eq () {
    for i in {1..8}; do 
        if [ ! a == "$i" ]; then
            return 1
        fi
    done
    return 0
}

[ ! a == "$i" ] checks if value of variable i ($i) is not equal to a.


You can leverage short circuit evaluation, || (runs the command following it only if the preceding command fails) too, here we will do the equity check [ a == "$i" ]:

check_all_1_to_8_eq () {
    for i in {1..8}; do 
        [ a == "$i" ] || return 1
    done
    return 0
}