Accessing Shell Script Arguments

The so-called positional parameters represent a shell script's command-line arguments. They also represent a function's arguments within shell functions. Individual arguments are named by integer numbers. For historical reasons, you have to enclose the number in braces if it's greater than nine:

echo first arg is $1
echo tenth arg is ${10}

Special "variables" provide access to the total number of arguments that were passed, and to all the arguments at once. We provide the details later, in Section 6.1.2.2.

Suppose you want to know what terminal a particular user is using. Well, once again, you could use a plain who command and manually scan the output. However, that's difficult and error prone, especially on systems with lots of users. This time what you want to do is search through who's output for a particular user. Well, anytime you want to do searching, that's a job for the grep command, which prints lines matching the pattern given in its first argument. Suppose you're looking for user betsy because you really need that flag you ordered from her:

$ who | grep betsy                      
            Where is betsy?
betsy      pts/3        Dec 27 11:07    (flags-r-us.example.com)

Now that we know how to find a particular user, we can put the commands into a script, with the script's first argument being the username we want to find:

$ cat > finduser                        
            Create new file
            #! /bin/sh

            # finduser --- see if user named by first argument is logged in

            who | grep $1
            ^D                                      
            End-of-file

$ chmod +x finduser                     
            Make it ...

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.