Reading the Output of a Sequence of Commands in a variable.
In the previous video, we've learned about
functions and arguments.
This video illustrates how to combine multiple commands
and how its output can be read.
One of the best design features of shell scripting
is the ease of combining many commands
or utilities to produce output.
The output of one command can appear as the input of another
which passes its output to another command, and so on.
The output of this combination can be read in a variable.
Inputs usually feed into a command
through STDIN or arguments.
Output appears as STDERR or STDOUT.
While we combine multiple commands,
we usually use STDIN to give input
and STDOUT to provide an output.
In this context, the commands are called filters.
We connect each filter using pipes,
the piping operator.
Let's see an example.
Here we combine three commands.
The output of command1 go to command2
and the output of command2 go to command3
and the final output which comes out of command3
will be printed, or it could be redirected to a file.
Let's see how to do it.
We typically use pipes and use them with the
subshell method but combining outputs of multiple files.
Let's start with compiling two commands.
Here the output of ls, the listing the current directory,
is passed to cat -n, which in turn puts the line numbers
to the input we received through STDIN.
Therefore, its output is redirected to the out.txt file.
We can read the output of a sequence of commands
combined by pipes as...
This is called subshell method.
For example...
Another method called backquotes,
some people also refer to it as backtick,
can also be used to store the command output as...
For example, backquote is different from
the single quote character.
It is the character on the tilde button on the keyboard.
There are multiple ways of grouping commands.
Let's go through a few of them.
Spawning a separate process with subshell.
Subshells are separate processes.
A subshell can be defined using
the open close bracket operators as...
When some commands are executed in a subshell,
none of the chances occur in the current shell.
Changes are restricted to the subshell.
For an example, when the current directory in a subshell
has changed using the cd command,
the directory change is not reflected
in the main shell environment.
The pwd command prints the path of the working directory.
The cd command changes the current directory
to the given directory path.
Subshell quoting to preserve spacing
and the new line character.
Suppose we're reading the output
of a command to a variable using a subshell
or the backquotes method.
We always quote them in double quotes
to preserve the spacing and new line character /n.
For example.
Also, we've successfully learned how to read
the output of sequence of commands and your variable.
In the next video,
we'll learn how to read n characters
without pressing the return key.