Interview Prep/Shell Scripting/ShellCheck, debugging, testing, portability and security

How do you make `set -x` output more useful with `PS4`?

IntermediateConceptShellCheck, debugging, testing, portability and security
Answer

PS4 is the prefix printed before each traced command (default + ). It is expanded every time, so it can include the location:

export PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
bash -x ./deploy.sh
# + deploy.sh:42:rollout: kubectl rollout status deploy/api --timeout=120s

Use single quotes so the variables expand at trace time. Add $(date +%T) to spot slow steps, at the cost of a fork per command.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on ShellCheck, debugging, testing, portability and security