How to pipe output to stdout and variable?

Viewed 890

When I run the following script, output of ls -la is stored to variable $output.

#! /bin/sh

output=$(ls -la)

How can I pipe output of ls -la to stdout and $output?

I am asking in the context of running borgbackup which can output for a long time during backups.

I would like to be able to track progress when I manually run script while storing output in $output to send it to sysadmin via email.

2 Answers

Use tee;

output=$(ls -lta | tee /dev/tty)

Another way of doing this is by creating a copy of STDOUT, and again using tee to send the output there;

# Create copy of stdout
exec 3>&1

# Run command
output=$(ls -lta | tee /dev/fd/3)

# Close copy
exec 3>&-

Use tee util and pass it to /dev/tty to print stdout.

box: ~/demo
āžœ out=$(ls -la | tee /dev/tty)
total 16
drwxr-xr-x    4 chen  staff   128 Feb 15 15:59 .
drwxr-xr-x+ 103 chen  staff  3296 Feb 15 15:59 ..
-rw-r--r--    1 chen  staff   141 Sep  1 12:38 docker-compose.yml
-rw-r--r--    1 chen  staff    84 Sep  1 12:31 ubuntu.Dockerfile
box: ~/demo
āžœ echo $out
total 16
drwxr-xr-x    4 chen  staff   128 Feb 15 15:59 .
drwxr-xr-x+ 103 chen  staff  3296 Feb 15 15:59 ..
-rw-r--r--    1 chen  staff   141 Sep  1 12:38 docker-compose.yml
-rw-r--r--    1 chen  staff    84 Sep  1 12:31 ubuntu.Dockerfile
Related