0

I want to create a bash script which does following:

  • write stdout and stderr to terminal
  • write stdout and stderr to info.log and prefix it with date and time
  • write stderr to error.log and prefix it with date and time
  • call multiple other bash scripts and exit if one does not exit with 0
  • exit with same exit code from first failing script

In my current script, the output in the terminal is not in chronological order... seems that the redirection with tee does something asynchronous.

Here is my current script:

#!/bin/bash

info_log_path="info.log"
error_log_path="error.log"

bashtrap()
{
   echo "Job finished with Exitcode $?"; exit $?;
}

trap bashtrap EXIT ERR

#exit on first errror:
#set -e

# redirect stdout and stderr to info log
exec &> >( tee >(while IFS= read -r line; do printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$line"; done >>"$info_log_path"))
# redirect stderr to error log
exec 2> >( tee >(while IFS= read -r line; do printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$line"; done >>"$error_log_path"))

echo "Executing script1"
./script1

echo "Executing script2"
./script2

echo "Executing script3"
./script3

echo "Executing script4"
./script4
tripleee
  • 175,061
  • 34
  • 275
  • 318
warch
  • 2,387
  • 2
  • 26
  • 43
  • 1
    You set your trap for `EXTI`, not for `ERR`. The latter is what would give you `set -e` behavior. Though why don't you simply use `set -e`? – tripleee Oct 12 '20 at 10:12
  • thx the trap mistake solved the first problem :) – warch Oct 12 '20 at 10:13
  • There is no way really to ensure that stderr and stdout print in a specific order. You can probably get something close to what you hope for by disabling buffering. – tripleee Oct 12 '20 at 10:30
  • how could i do that? without redirection the output is in order... it should be possible that redirection is sequential too – warch Oct 12 '20 at 10:32
  • I think its because of exec... Can i redirect the output without exec? – warch Oct 12 '20 at 10:36
  • The `exec` is not the problem. Google output buffering. – tripleee Oct 12 '20 at 10:49
  • Possible duplicate of https://stackoverflow.com/questions/3465619/how-to-make-output-of-any-shell-command-unbuffered – tripleee Oct 12 '20 at 10:55
  • 2
    Note that `while read; do print $(date)` will be _very_ slow. Consider using `awk` for adding timestamp to lines _magnitudes_ faster. – KamilCuk Oct 12 '20 at 11:29
  • i tried to get rid of buffering with ´´´stdbuf -i0 -o0 -e0´´´ but it did not work. any ideas? where i need to disable buffering? – warch Oct 12 '20 at 12:57

0 Answers0