Skip to content

Instantly share code, notes, and snippets.

@jahkeup
Last active May 26, 2023 22:17
Show Gist options
  • Save jahkeup/432ad7fb32dbc5ec2445ad8edebf7e67 to your computer and use it in GitHub Desktop.
Save jahkeup/432ad7fb32dbc5ec2445ad8edebf7e67 to your computer and use it in GitHub Desktop.
Run bash and log its STDOUT/STDERR to systemd journal
#!/usr/bin/env bash
# jakeev@
if [[ "${LOGBASH_ENABLE:-1}" -ne 0 ]]; then
declare -r PROGNAME="${0##*/}"
declare -r logid="${PROGNAME:-logbash}"
# retain actual stdout/stderr descriptors
exec {stderr}>&2
exec {stdout}>&1
# use systemd-cat to capture output
exec {journal}> >(systemd-cat -t "$logid" --level-prefix=false)
# wire up stdout/stderr to write to both stdout/stderr *AND* the journal.
exec {logstdout}> >(tee "/proc/self/fd/$journal" >"/proc/self/fd/$stdout")
exec {logstderr}> >(tee "/proc/self/fd/$journal" >"/proc/self/fd/$stderr")
exec >&"$logstdout" 2>&"$logstderr"
fi
exec bash "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment