From 2549b02e6f8e6fd7c8aba2f70392857a04bcd5f9 Mon Sep 17 00:00:00 2001 From: "Peter M. Elias" Date: Tue, 20 Oct 2020 07:33:12 -0500 Subject: [PATCH] add alternative to command substitution for func return --- README.md | 19 +++++++++++++++++++ manuscript/chapter19.txt | 20 ++++++++++++++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 79ca77a..4b1d011 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ See something incorrectly described, buggy or outright wrong? Open an issue or s * [Bypass shell aliases](#bypass-shell-aliases) * [Bypass shell functions](#bypass-shell-functions) * [Run a command in the background](#run-a-command-in-the-background) + * [Capture function return without command substitution](#capture-the-return-value-of-a-function-without-command-substitution) * [AFTERWORD](#afterword) @@ -2169,6 +2170,24 @@ bkr() { bkr ./some_script.sh # some_script.sh is now running in the background ``` +## Capture the return value of a function without command substitution + +**CAVEAT:** Requires `bash` 4+ + +This uses local namerefs to avoid using `var=$(some_func)` style command substitution for function output capture. + +```sh +to_upper() { + local -n ptr=${1} + + ptr=${ptr^^} +} + +foo="bar" +to_upper foo +printf "%s\n" "${foo}" # BAR +``` + # AFTERWORD diff --git a/manuscript/chapter19.txt b/manuscript/chapter19.txt index 85ef650..56f5178 100644 --- a/manuscript/chapter19.txt +++ b/manuscript/chapter19.txt @@ -219,10 +219,26 @@ This will run the given command and keep it running, even after the terminal or bkr() { (nohup "$@" &>/dev/null &) } + +bkr ./some_script.sh # some_script.sh is now running in the background ``` -```shell -bkr ./some_script.sh # some_script.sh is now running in the background +## Capture the return value of a function without command substitution + +**CAVEAT:** Requires `bash` 4+ + +This uses local namerefs to avoid using `var=$(some_func)` style command substitution for function output capture. + +```sh +to_upper() { + local -n ptr=${1} + + ptr=${ptr^^} +} + +foo="bar" +to_upper foo +printf "%s\n" "${foo}" # BAR ```