Skip to content

Instantly share code, notes, and snippets.

@hypnoglow
Last active January 23, 2023 18:42
Show Gist options
  • Save hypnoglow/6b89927d5156bc5e37e0e8dc67c780da to your computer and use it in GitHub Desktop.
Save hypnoglow/6b89927d5156bc5e37e0e8dc67c780da to your computer and use it in GitHub Desktop.
Bash trick to return string from function - 10x faster than using subshell like $(cmd)
function assign() {
unset -v "$1" || echo "Invalid identifier: $1" >&2
printf -v "$1" '%s' "$2"
}
function getHelloWorld() {
# Return the value "Hello World!"
local "$1" && assign "$1" "Hello World!"
}
# Note: No $ here - we are specifying a name of a variable, not the value of a variable.
getHelloWorld SOME_VAR
echo "$SOME_VAR" # Echos "Hello World!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment