Skip to content

Instantly share code, notes, and snippets.

@GrabbenD
Last active July 22, 2024 11:24
Show Gist options
  • Save GrabbenD/01803465f4c2413bf7103caa15dc6791 to your computer and use it in GitHub Desktop.
Save GrabbenD/01803465f4c2413bf7103caa15dc6791 to your computer and use it in GitHub Desktop.
runuser: execute commands without use of quotation marks
#!/usr/bin/env bash
# Persistent variables
declare -g VARIABLES=( "import=works" "env=var" )
declare -g EXAMPLE="WONTBEIMPORTED"
# Isolated commands to be executed in a clean environment
function SANDBOX_RUN {
echo "${USER}" # = build
whoami # = build
ls -d ~/ # = /home/build/
echo IMPORTED: "${import:-}" # = IMPORTED: works
echo EXAMPLE: "${EXAMPLE:-}" # = EXAMPLE:
}
# Global verbosity
function MAIN_DEBUG {
set -x
}
# Main logic <----
function MAIN_RUN {
local ENV=("$(declare -p VARIABLES);" $'[[ -n "${VARIABLES:-}" ]] && declare -g "${VARIABLES[@]}"') # Import variables to subprocess through serialized list
local CMD=("$(declare -f "${@}");" "{ ${*/%/;} }") # Import functions by printing escaped contents
# Treat each Bash argument as a command through eval and parameter expansion whilst RUNNER is the cosmetic name of the caller ($0)
exec runuser --login build --shell /usr/bin/bash -- -c $'eval "${@/%/;}"' RUNNER "${ENV[*]}" "${CMD[*]}"
}
# What to run
function MAIN {
MAIN_DEBUG # Enable Bash debugging
MAIN_RUN MAIN_DEBUG SANDBOX_RUN # Execute functions inside sandbox
}
MAIN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment