Linux – Bash script redirect all output to file

bashlinux

I have following script that works fine on desktop CentOS 7, but it does not work correct on server CentOS 7 on digitalocean droplet.

The problem is that it does not auto exit on complete, I have to press enter to exit

#!/bin/bash

LOG_FILE=/var/log/mylog.log

if [ -f $LOG_FILE ]; then
  mv $LOG_FILE $LOG_FILE.$(date +%s)
fi

exec > >(tee -a -i $LOG_FILE)
exec 2>&1

echo "track 1x"
echo "track 2x"

Best Answer

Another possible way to structure this code in a way that won't trigger this race condition is to group the rest of the code inside a { ... } block and pipe that to tee.

That way, bash will be guaranteed to wait() for tee to complete before ending the script.

#!/bin/bash

LOG_FILE=/var/log/mylog.log

if [[ -f "$LOG_FILE" ]]; then
  mv "$LOG_FILE" "$LOG_FILE.$(date +%s)"
fi

{
  echo "track 1x"
  echo "track 2x"
} 2>&1 | tee -a -i "$LOG_FILE"
Related Question