Accepting Command-Line Arguments in Your Scripts


Suppose that at the end of every month you need to send a progress report to your boss. You might set up a script to address an email message to your boss, provide an appropriate subject line, and send the file containing the progress report. You'd likely have this script automatically address a message to your boss and put in the subject line, but you'd want to use command-line input to tell the script which file you want to send. By using command-line input, you can give your scripts a bit more flexibility and still have much of a process automated for you. You run the script and specify the input at the shell prompt, as shown in Figure 10.7.

Figure 10.7. Using command-line input, you can add flexibility to a script and still have the script do the grunt work for you.


To Accept Command-Line Arguments in a Script:

1.

vi status-report

Use your favorite editor to edit your script.

2.

mail -s "Status report for $1" boss@example.com < ~/reports/$1

Enter a command, with $1 appearing in each place you want to use the first item of input from the command line. In this example, the script starts a message to the boss, fills in the subject line (adding the month automatically), and sends the appropriate monthly report (the one specified on the command line) from the reports directory under your home directory.

3.

Save and exit, and then run the script (Code Listing 10.6), though you might first have to find a boss to take your status report and provide the content for the status report.

Code Listing 10.6. By providing command-line input, you can control what the script does.

[ejr@hobbes scripting]$ more status- report #! /bin/sh mail boss@whereever.com -s "Status report  for $1 < ~/reports/$1 [ejr@hobbes scripting]$ ./status-report  August [ejr@hobbes scripting]$ 

Tips

  • To see the information provided at the command line, echo it back out with echo $*. The $* variable provides all of the command-line input, with $1, $2, and $3 containing the individual items.

  • You can also accept input at specified points while a script is running. See the next section for more details.





Unix(c) Visual Quickstart Guide
UNIX, Third Edition
ISBN: 0321442458
EAN: 2147483647
Year: 2006
Pages: 251

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net