Skip to content

Commit

Permalink
add alternative to command substitution for func return
Browse files Browse the repository at this point in the history
  • Loading branch information
txbm committed Oct 20, 2020
1 parent ea0ba69 commit 2549b02
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

<!-- vim-markdown-toc -->
Expand Down Expand Up @@ -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
```
<!-- CHAPTER END -->
# AFTERWORD
Expand Down
20 changes: 18 additions & 2 deletions manuscript/chapter19.txt
Original file line number Diff line number Diff line change
Expand Up @@ -219,11 +219,27 @@ This will run the given command and keep it running, even after the terminal or
bkr() {
(nohup "$@" &>/dev/null &)
}
```

```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
```

<!-- CHAPTER END -->

0 comments on commit 2549b02

Please sign in to comment.