Search code examples
linuxbashshellgentoo

What's wrong with this while loop multiple condition in bash


The multiple condition as shown below, it's working fine with the ideal text file, but the actual output of my code should have some extra lines.

while loop multiple condition:

while read -r line && ([[ ! "${line/"[ebuild"}" = "${line}" ]] && [[ -n "${line}" ]])
do
   echo "This is the line:      $line."
done

If I modified the code to the below, it's working fine.

while read -r line 
do
   if [ ! "${line/"[ebuild"}" = "${line}" ] && [ -n "${line}" ]; then
        echo "This is the line:      $line."
   fi
done

Ideal text file:

[ebuild   R    ] app-arch/xz-utils-5.2.2::gentoo  USE="nls static-libs* threads" 0 KiB
[ebuild   R    ] sys-libs/zlib-1.2.8-r1::gentoo  USE="static-libs -minizip" 0 KiB
[ebuild   R    ] virtual/libintl-0-r2::gentoo  0 KiB
...

Actual text file:

These are the packages that would be merged, in order:

Calculating dependencies  ... done!
[ebuild   R    ] app-arch/xz-utils-5.2.2::gentoo  USE="nls static-libs* threads" 0 KiB
[ebuild   R    ] sys-libs/zlib-1.2.8-r1::gentoo  USE="static-libs -minizip" 0 KiB
[ebuild   R    ] virtual/libintl-0-r2::gentoo  0 KiB

What's wrong with it? Thank you very much!


Solution

  • A while loop executes until the condition is false; then it stops looping and continues below. The second version does what you want: loop while until end of file, but only execute the body (the echo command) if the line meets certain conditions.

    The first version, on the other hand, runs the loop until either the end of file OR it reads a line that doesn't meet the conditions. Since the first line doesn't meet those conditions, it exits the loop immediately and never gets to the lines that do meet the conditions.