Search code examples
zsh

zsh: create named file in place of argument?


realpath <<<'foo' fails "realpath: missing operand". I don't know what that means.

realpath <(<<<'foo') returns /proc/3443695/fd/pipe:[26244650] which I guess means it's creating a temporary pipe which will contain the string "foo".

Or maybe printf is more clear:

❯ printf "%q" <<<'foo'  # no output
❯ printf "%q" <(<<<'foo')
/proc/self/fd/11%   

The actual program I'm trying to call doesn't like either of those. I think I need an actual file.

I can do that in multiple commands by creating a file with mktemp and then writing to it, and then sending that off as the arg, but does zsh have any convenient syntax for doing this in-place? A 1-liner?


Solution

  • It looks like the =(list) process substitution should do what you want.

    From the zshexpn man page:

    If =(...) is used instead of <(...), then the file passed as an argument will be the name of a temporary file containing the output of the list process. This may be used instead of the < form for a program that expects to lseek on the input file.
    ...
    The temporary file created by the process substitution will be deleted when the function exits.

    On my system, realpath =(<<<'foo') returns something like /private/tmp/zsh3YAdDx, i.e. the name of a temporary file that does indeed appear to be deleted after executing the command.

    As a bonus, the documentation notes that in some cases the =(<<<...) form is optimized to execute completely in the current shell.