pass stdout as file name for command line util?

前端 未结 5 2059
醉酒成梦
醉酒成梦 2020-11-30 03:23

I\'m working with a command line utility that requires passing the name of a file to write output to, e.g.

foo -o output.txt

The only thing

相关标签:
5条回答
  • 2020-11-30 03:41

    For the sake of making stackoverflow happy let me write a long enough sentence because my proposed solution is only 18 characters long instead of the required 30+

    foo -o /dev/stdout
    
    0 讨论(0)
  • 2020-11-30 03:43

    You could use the magic of UNIX and create a named pipe :)

    1. Create the pipe

      $ mknod -p mypipe
      
    2. Start the process that reads from the pipe

      $ second-process < mypipe
      
    3. Start the process, that writes into the pipe

      $ foo -o mypipe
      
    0 讨论(0)
  • 2020-11-30 03:43

    I use /dev/tty as the output filename, equivalent to using /dev/nul/ when you want to output nothing at all. Then | and you are done.

    0 讨论(0)
  • 2020-11-30 03:46

    Solution 1: Using process substitution

    The most convenient way of doing this is by using process substitution. In bash the syntax looks as follows:

    foo -o >(other_command)
    

    (Note that this is a bashism. There's similar solutions for other shells, but bottom line is that it's not portable.)

    Solution 2: Using named pipes explicitly

    You can do the above explicitly / manually as follows:

    1. Create a named pipe using the mkfifo command.

      mkfifo my_buf
      
    2. Launch your other command with that file as input

      other_command < my_buf
      
    3. Execute foo and let it write it's output to my_buf

      foo -o my_buf
      

    Solution 3: Using /dev/stdout

    You can also use the device file /dev/stdout as follows

    foo -o /dev/stdout | other_command
    
    0 讨论(0)
  • 2020-11-30 03:47

    Named pipes work fine, but you have a nicer, more direct syntax available via bash process substitution that has the added benefit of not using a permanent named pipe that must later be deleted (process substitution uses temporary named pipes behind the scenes):

    foo -o >(other command)

    Also, should you want to pipe the output to your command and also save the output to a file, you can do this:

    foo -o >(tee output.txt) | other command

    0 讨论(0)
提交回复
热议问题