This commit is contained in:
Mitchell Perilstein 2020-10-22 01:33:03 -07:00 committed by GitHub
commit a9b74d5fb3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 98 additions and 1 deletions

View File

@ -1032,6 +1032,48 @@ echo -n >file
printf '' >file
```
## Use `exec` to redirect script output to different file descriptors
`exec` can be used to redirect script output to file descriptors. In the example below, `stdout` and `stderr` are redirected to `myoutput.log` (a file).
**Example Function:**
```sh
log_all_output() {
# Usage: log_all_output log_filename
exec 6>&1 # save stdout
exec 7>&2 # save stderr
exec &>"$1"
}
stop_logging_output() {
exec 1>&6 6>&- # Restore stdout
exec 2>&7 7>&- # Restore stderr
}
```
**Example Usage:**
```shell
# These are *not* logged.
printf 'This is a message.\n'
printf 'This is an error message.\n' >&2
# All script output will go to 'myoutput.log'.
log_all_output myoutput.log
# These are now logged.
printf 'This is a message.\n'
printf 'This is an error message.\n' >&2
# Return to normal.
stop_logging_output
# These are not logged.
printf 'This is a message.\n'
printf 'This is an error message.\n' >&2
```
## Extract lines between two markers
**Example Function:**

View File

@ -164,6 +164,48 @@ echo -n >file
printf '' >file
```
## Use `exec` to redirect script output to different file descriptors
`exec` can be used to redirect script output to file descriptors. In the example below, `stdout` and `stderr` are redirected to `myoutput.log` (a file).
**Example Function:**
```sh
log_all_output() {
# Usage: log_all_output log_filename
exec 6>&1 # save stdout
exec 7>&2 # save stderr
exec &>"$1"
}
stop_logging_output() {
exec 1>&6 6>&- # Restore stdout
exec 2>&7 7>&- # Restore stderr
}
```
**Example Usage:**
```shell
# These are *not* logged.
printf 'This is a message.\n'
printf 'This is an error message.\n' >&2
# All script output will go to 'myoutput.log'.
log_all_output myoutput.log
# These are now logged.
printf 'This is a message.\n'
printf 'This is an error message.\n' >&2
# Return to normal.
stop_logging_output
# These are not logged.
printf 'This is a message.\n'
printf 'This is an error message.\n' >&2
```
## Extract lines between two markers
**Example Function:**

15
test.sh
View File

@ -205,6 +205,19 @@ test_split() {
assert_equals "${result[*]}" "hello world my name is john"
}
test_log_all_output() {
(
log_all_output test.log
printf stdout
printf stderr >&2
stop_logging_output
printf stdout
printf stderr >&2
) &> /dev/null
contents="$(<test.log)"
assert_equals "$contents" "stdoutstderr"
}
assert_equals() {
if [[ "$1" == "$2" ]]; then
((pass+=1))
@ -219,7 +232,7 @@ assert_equals() {
}
main() {
trap 'rm readme_code test_file' EXIT
trap 'rm readme_code test_file test.log' EXIT
# Extract code blocks from the README.
while IFS=$'\n' read -r line; do