4.Shell Scripting 1
4.Shell Scripting 1
• The | (pipe) connects input and output streams together so that one command takes input from the
other.
• You know the who command produces a list of users, one user per line. Let’s use redirection to
save this output in a file:
• Let’s now use we to make a complete count of this file’s contents. We’ll use the -l option to
count the number of lines only, and redirect wc’s input so that the filename doesn’t appear in
the output:
Pipe (|)
• Using an intermediate file (user. txt), we effectively counted the number of users. This method
of running two commands separately has two obvious disadvantages:
1. For long-running commands, this process can be slow. The second command can’t act
unless the first has completed its job.
2. You require an intermediate file that has to be removed after completion of the job.
When handling large files, temporary files can build up easily and eat up disk space
quickly.
• The shell can connect these streams using a special operator—the | (pipe) and avoid the
creation of the disk file. You can make who and wc work in tandem so that one takes input
from the other:
Pipe (|)
• There’s no restriction on the number of commands you can use in a pipeline. But you must
know the behavioral properties of these commands to place them there.
• let’s use the we command to display the total size of all C programs:
• To display both the list of users and its count on the terminal, you can use the device name
/dev/tty as an argument to tee:
for Loops
• for loops allow the repetition of a command for a specific set
of values
• Syntax:
for var in value1 value2 ...
do
command_set
done
• command_set is executed with each value of var (value1, value2,
...) in sequence
for Loop Example (1)
#!/bin/sh
# timestable – print out a multiplication table
for i in 1 2 3
do
for j in 1 2 3
do
value=`expr $i \* $j`
echo -n "$value "
done
echo
done
for Loop Example (2)
#!/bin/sh
# loop over files
files=`ls`
for i in $files
do
echo -n "$i "
done
#!/bin/sh
x=1
until [ $x -gt 3 ]; do
echo x = $x
x=`expr $x + 1`
done
The select Loop
• The select loop provides an easy way to create a numbered
menu from which users can select options.
• Not available in sh.
• Syntax: