-4

What this is the following command doing? I'm new, and still learning.

$ sh < foo > bar

How to interpret it step by step so that I can get clear understanding more question like this.

Kusalananda
  • 333,661

2 Answers2

0

Let's break it down. This command has three parts:

sh

sh is the name of the program to be run, in this case, it's the sh.

< foo

< simbol says that the word following it is the name of a file and commands the shell(shell which executes the command, it has nothing to do with sh, the program being called, which happens to be a shell) to join the standard input of the program to the contents of file whose name follows the symbol, foo in this case.

> bar

> symbol commands the shell to join the standard output of the program being executed to the file bar.

These redirection paths are setup before the execution of the program begins.

So the whole command, sh < foo > bar, when run on a shell. makes the program sh read commands from file foo and store it's output in the file bar. It's an error if the file foo doesn't exist. The behavior of the shell depending on whether file bar exists or not is determined by the noclobber option of the shell you use.

saga
  • 1,401
0

In general,

$ utility <input >output

will cause utility to be executed with its standard input stream connected to the file input and its standard output stream connected to the file output.

The $ at the start of the line is the shell prompt (you will not type this).

In the case of sh, which is a shell command interpreter, this will cause sh to read and execute the shell commands from the input file (foo in your case) and write any output to the output file (bar in your case). Diagnostic messages (errors and warnings) will still be displayed on the terminal since these are usually written to the standard error stream, which the command line that you mentioned does not redirect anywhere in particular.

The command that you mentioned has more or less the same effect as

$ sh foo >bar

since sh is able to read from the file mentioned on its command line and will only read from the standard input stream if no file is mentioned.

Kusalananda
  • 333,661
  • Note that those redirections (the new resources now attached to stdin and stdout) are inherited by all the commands started by that sh. That's a big difference between sh < foo and sh foo: for the commands in that foo script, stdin will be the foo file in the sh < foo case. – Stéphane Chazelas Jun 04 '17 at 11:12