Create a temporary file from a stdout redirect or pipe

11,754

Solution 1

You could use < to redirect your output to stdin.

I don't know how meld works, but about your diff example, here's how it would work:

Using tempfiles

$ cmd1 > file1.tmp
$ cmd2 > file2.tmp
$ diff file1.tmp file2.tmp

Without tempfiles

$ diff <(cmd1) <(cmd2)

Note that syntax may vary a bit according to the shell you're using (I'm using ksh88).

Solution 2

mktemp will create a temporary filename for you. Save the filename in a variable, and use that in both slots.

For a better solution for your precise problem, check out git difftool. I have mine setup to use meld, and it's pretty great.

Solution 3

I've never used meld but you can accomplish this typically using the - argument to most cli utilities. e.g.

cat /path/to/left/file | diff /input/from/right/file -

Specifically for your meld command you might try something like:

git show HEAD:$1 | meld - $1
Share:
11,754

Related videos on Youtube

Vayn
Author by

Vayn

Updated on September 18, 2022

Comments

  • Vayn
    Vayn over 1 year

    Some commands only output to stdout.
    Some tools only work on files.
    Is there a command that can glue those together?

    Contrived simple example:

    diff $(echo 1 | stdout-to-temp-file) $(echo 2 | stdout-to-temp-file)

    My actual use case; Current workaround:

    git show HEAD:$1 > /tmp/left && meld /tmp/left $1

    My actual use case; Desired:

    meld $(git show HEAD:$1 | stdout-to-temp-file) $1

    I'd use this in a few other situations too (i.e. I'm not looking for a git or meld only fix).

  • ConcernedOfTunbridgeWells
    ConcernedOfTunbridgeWells over 12 years
    This is the right way to go - much better than using a fixed file name.
  • Peter.O
    Peter.O over 12 years
    +1, but that's not redirection. It is Process Substitution ... Process substitution uses /dev/fd/<n> ... eg gedit <(echo Hello) will open a file named 63 or some such fd number, and the "Hello", which was sent to stdout, simply vanishes into the bit-bucket of that process, because gedit doesn't accept stdin, eg echo Hello | gedit.
  • rozcietrzewiacz
    rozcietrzewiacz over 12 years
    +1 for both mktemp and difftool. An alternative to mktemp is tempfile or a file name composed using $$ variable (less secure).
  • frogstarr78
    frogstarr78 over 12 years
    oops initial diff command was incorrect
  • Shawn J. Goff
    Shawn J. Goff over 12 years
    Process substitution isn't POSIX standard, and isn't available on every shell out there, so be aware of that if you're using it in a script.