Fixing out-of-order message output when piping snapcraft's output to file

The following command:

snapcraft build wxwidgets-3-0 2>&1 \
    | tee build.wxwidgets-3-0.snapcraft.log

results in out-of-order message output, like this:

+ snapcraftctl build
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu

   ...lots of messages later...

+ rm --force --recursive --verbose "${SNAPCRAFT_PART_INSTALL}"/root/.*
rm: refusing to remove '.' or '..' directory: skipping '/root/build_wxwidgets/parts/wxwidgets-3-0/install/root/..'
./configure --prefix= --prefix=/root/build_wxwidgets/stage
make -j4
make install DESTDIR=/root/build_wxwidgets/parts/wxwidgets-3-0/install
Failed to run 'override-build': Exit code was 1.

Note the last 1-3 lines, which should appear right after + snapcraftctl build but presented at the very end instead.

This seems to be due to the fact that stdout is by default buffered but stderr isn’t, which can be solved by using unbuffer command provided by the expect package:

$ unbuffer snapcraft build wxwidgets-3-0 2>&1 \
    | tee build.wxwidgets-3-0.snapcraft.log
+ snapcraftctl build
./configure --prefix= --prefix=/root/build_wxwidgets/stage
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking for --disable-gui... no

...REDACTED...

rm: refusing to remove '.' or '..' directory: skipping '/root/build_wxwidgets/parts/wxwidgets-3-0/install/root/build_wxwidgets/stage/..'
+ true
+ cd /root/build_wxwidgets/parts/wxwidgets-3-0/install
+ rmdir --ignore-fail-on-non-empty --parents --verbose root/build_wxwidgets/stage
rmdir: removing directory, 'root/build_wxwidgets/stage'
rmdir: removing directory, 'root/build_wxwidgets'
rmdir: removing directory, 'root'
+ cd -
+ ln --force --relative --symbolic /root/build_wxwidgets/stage/lib/wx/config/* /root/build_wxwidgets/stage/bin/wx-config

References