bashvariablesstreampipetee

Bash: How to capture output of an "inner" tee in WSL


Currently, I am using the following (working) command in order to compress and encrypt some folders:

backup_folders "${srcFolders}" - $@ | encrypt > "${targetFile}"

backup_folders and encrypt are self-written Bash functions doing what their name says. backup_folders will create a tar.gz archive and write it to stdout in order to pipe it to further processing steps like encrypt above.

Now I would like to know the date of the newest file in the archive stream. To accomplish this, I added the following function:

get_newest_content() {
  local newestDate=$(tar --list --verbose --xz --full-time | awk '{ print $4 $5}' | sort -r | head -1)
  >&2 echo "Newest date of archive: ${newestDate}"
}

Then I updated my command from above to include this function like this:

backup_folders "${srcFolders}" - $@ | tee >(get_newest_content) | encrypt > "${targetFile}"

This is also working insofar as that the newest date is correctly determined and printed out (ignoring some formatting issues for now). But I would rather like to have this information contained in a variable. Thus, I need to capture the output of the function tee'd in the inner pipe.

I have tried the solutions mentioned here on SO and also here, all pointing towards writing the output from get_newest_content to another stream, e. g. like this (I tried multiple variations):

{ date=$(backup_folders "${srcFolders}" - $@ | tee >(get_newest_content) | encrypt > "${targetFile}"); } 2>&1

Unfortunately, I did not succeed, date is always empty or any value I initialized it with for testing.

As I am working under WSL (at least I guess, this is the reason...), I don't have /dev/fd/3 and higher available. (Just 0, 1, 2 and 255). I tried with 255 as well, but did not succeed.

Not being a very experienced Bash developer, I would like to kindly ask for help now. Probably, the solution is quite simple and the problem is sitting in front of the monitor. ^^


Solution

  • You're looking for something like this:

    date=$({ backup_folders "${srcFolders}" - $@ | tee >(get_newest_content >&3) | encrypt > "${targetFile}";} 3>&1)