Bash one-liner to save to file then use content

Viewed 72

I'm trying to do something like this:

  1. save command1 output to file
  2. feed same output to command2

something like this

   command2 $(command1 > file.txt)

but that didn't work.

2 Answers

Use tee. This copies its standard input to a file and also its standard output. Then pipe the output to the second command.

command1 | tee file.txt | command2

Your question used

command2 $(command1 > file.txt)

tee pipes are great, but if I read this right, command2 expects a filename? If so, maybe you can use

command2 <( command1 )

If you also need the file, then tee inside the construct -

command2 <( command1 | tee file.txt )

If for some strange reason it absolutely requires a file NAME (can't really imagine why), then you could always try this as a last resort -

command2 "$( command1 > file.txt && echo file.txt )"
Related