Last active
January 23, 2023 18:42
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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