2

I'm working on a lab assignment for a class, which exemplifies users | wc -w as displaying the number of users currently logged in. The instructor has asked we write the output of users to a file (users > file), while still displaying the count. My initial thought was to change the original example to simply read users > file | wc -w, but I receive the error:

ambiguous output redirect

Our college's Unix lab has us working, by default in tcsh, and I know the commands can differ between the shells. Is there a command that can accomplish this that I'm completely forgetting?

2

Use tee:

users | tee file | wc -w

Gives as output the number of users, and it writes a file with the users as content.


The case in your question:

command >file | command2

This cannot work. With >file you redirect the ouput of command to the file file and in the same the output is written to an anonymous pipe, where the command command2 reads at the other end. This is an ambiguous redirection.

The tee command will accept a file as argument, in which tee writes everything it recieves from its standard input. tee also writes everything from standard input to its standard output, where you can redirect to further commands or files.

  • 1
    It's perhaps useful to mention that the name "tee" is named after a T-splitter, which is exactly what the commands does: take some input, and "split" it to both stdout and a file; you can then further pipe stdout to other processes (wikipedia has a nice image of this). – Martin Tournoij Sep 23 '15 at 17:57
  • @Carpetsmoker Good image, that's the T, didn't know that. BTW: the manpage of tee is also very concise: tee - read from standard input and write to standard output and files – chaos Sep 23 '15 at 17:59
  • Okay, thanks! I had visited the man page for tee, but it sort of threw me off, I wasn't sure that was what I needed. – Brad B Sep 23 '15 at 18:13
1

There is a command to accomplish this; it's called tee:

users | tee file | wc -w

PS. (External) commands do not differ between shells; input and output redirection syntax does vary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.