Skip to content

Instantly share code, notes, and snippets.

@mfrischknecht
Last active April 19, 2025 10:53
Show Gist options
  • Save mfrischknecht/fd1de53e6f77496ef4753aa5007091e5 to your computer and use it in GitHub Desktop.
Save mfrischknecht/fd1de53e6f77496ef4753aa5007091e5 to your computer and use it in GitHub Desktop.
Test script to test generic shell command with the environment of a specific systemd unit
#!/usr/bin/env bash
set -euo pipefail
function escape_shell_command() { for arg in "${@}"; do printf '%q ' "$arg"; done; }
command="$1"
unit="$2"
testUnit="test-$unit"
testCommand="$(escape_shell_command "${@:3}")"
systemdRunCommand="$(
systemctl show "$unit" \
| grep -E '(^(User|Group|Supplementary|Protect|Private|Restrict|Lock|NoNew|Environment|SystemCallFilter)|(Capabilit|Deny))' \
| while IFS= read -r property; do printf "%q\\n" "$property"; done \
| awk -v "unit=$testUnit" -v "command=${testCommand//\\/\\\\}" '
BEGIN { printf("\nsystemd-run --pty -u '\''%s'\'' --collect --wait \\\n", unit) }
/^EnvironmentFiles=/ {
prefix = ($0 ~ / \\\(ignore_errors=yes\\\)$/) ? "-" : "";
value = gensub(/^EnvironmentFiles=(.*)\\ \\\(ignore_errors=(yes|no)\\\)$/, "\\1", "g", $0);
printf("--property=EnvironmentFile=%s%s \\\n", prefix, value);
next;
}
1 { printf("--property=%s \\\n",$0) }
END { print "-- " command }
'
)"
if [[ "$command" != "run" ]]; then
echo "$systemdRunCommand";
exit
fi
start="$(date --iso=seconds)"
bash -c "$systemdRunCommand" || true
echo
echo Log:
journalctl -u "$testUnit" --since="$start" --no-pager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment