A Simple Script
Let's start with a simple script. Suppose that you'd like to know how many users are currently logged in. The who command tells you who is logged in:
$ who
george pts/2 Dec 31 16:39 (valley-forge.example.com)
betsy pts/3 Dec 27 11:07 (flags-r-us.example.com)
benjamin dtlocal Dec 27 17:55 (kites.example.com)
jhancock pts/5 Dec 27 17:55 (:32)
camus pts/6 Dec 31 16:22
tolstoy pts/14 Jan 2 06:42
On a large multiuser system, the listing can scroll off the screen
before you can count all the users, and doing that every time is painful
anyway. This is a perfect opportunity for automation. What's missing is
a way to count the number of users. For that, we use the wc (word count)
program, which counts lines, words, and characters. In this instance, we
want wc -l
, to count just
lines:
$ who | wc -l
Count users
6
The |
(pipe) symbol
creates a pipeline between the two programs: who's output becomes wc's input. The result, printed by wc, is the number of users logged in.
The next step is to make this pipeline into a separate command. You do this by entering the commands into a regular file, and then making the file executable, with chmod, like so:
$cat > nusers
Create the file, copy terminal input with catwho | wc -l
Program text^D
Ctrl-D is end-of-file $chmod +x nusers
Make it executable $./nusers
Do a test run 6 Output is what we expect
This shows the typical development cycle for small one- or two-line shell scripts: first, you experiment directly at the command line. ...
Get Classic Shell Scripting now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.