📄 ch44_16.htm
字号:
<HTML><!--Distributed by F --><HEAD><TITLE>[Chapter 44] 44.16 Handling Command-Line Arguments with a for Loop </TITLE><METANAME="DC.title"CONTENT="UNIX Power Tools"><METANAME="DC.creator"CONTENT="Jerry Peek, Tim O'Reilly & Mike Loukides"><METANAME="DC.publisher"CONTENT="O'Reilly & Associates, Inc."><METANAME="DC.date"CONTENT="1998-08-04T21:53:54Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-260-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch44_01.htm"TITLE="44. Shell Programming for the Uninitiated"><LINKREL="prev"HREF="ch44_15.htm"TITLE="44.15 Handling Command-Line Arguments in Shell Scripts "><LINKREL="next"HREF="ch44_17.htm"TITLE="44.17 Handling Arguments with while and shift "></HEAD><BODYBGCOLOR="#FFFFFF"TEXT="#000000"><DIVCLASS="htmlnav"><H1><IMGSRC="gifs/smbanner.gif"ALT="UNIX Power Tools"USEMAP="#srchmap"BORDER="0"></H1><MAPNAME="srchmap"><AREASHAPE="RECT"COORDS="0,0,466,58"HREF="index.htm"ALT="UNIX Power Tools"><AREASHAPE="RECT"COORDS="467,0,514,18"HREF="jobjects/fsearch.htm"ALT="Search this book"></MAP><TABLEWIDTH="515"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="172"><ACLASS="SECT1"HREF="ch44_15.htm"TITLE="44.15 Handling Command-Line Arguments in Shell Scripts "><IMGSRC="gifs/txtpreva.gif"SRC="gifs/txtpreva.gif"ALT="Previous: 44.15 Handling Command-Line Arguments in Shell Scripts "BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="171"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1">Chapter 44<BR>Shell Programming for the Uninitiated</FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="172"><ACLASS="SECT1"HREF="ch44_17.htm"TITLE="44.17 Handling Arguments with while and shift "><IMGSRC="gifs/txtnexta.gif"SRC="gifs/txtnexta.gif"ALT="Next: 44.17 Handling Arguments with while and shift "BORDER="0"></A></TD></TR></TABLE> <HRALIGN="LEFT"WIDTH="515"TITLE="footer"></DIV><DIVCLASS="SECT1"><H2CLASS="sect1"><ACLASS="title"NAME="UPT-ART-4940">44.16 Handling Command-Line Arguments with a for Loop </A></H2><PCLASS="para"><ACLASS="indexterm"NAME="AUTOID-51412"></A><ACLASS="indexterm"NAME="AUTOID-51415"></A>Sometimes you want a script that will step through the command-line argumentsone by one.(The<SPANCLASS="link"><CODECLASS="literal">"$@"</CODE> parameter (<ACLASS="linkend"HREF="ch44_15.htm"TITLE="Handling Command-Line Arguments in Shell Scripts ">44.15</A>)</SPAN> gives you all of them at once.)The Bourne shell <EMCLASS="emphasis">for</EM> loop can do this.The <EMCLASS="emphasis">for</EM> loop looks like this:</P><PCLASS="para"><BLOCKQUOTECLASS="screen"><PRECLASS="screen">for arg in <CODECLASS="replaceable"><I>list</I></CODE>do ...<EMCLASS="emphasis">handle $arg</EM>...done</PRE></BLOCKQUOTE></P><PCLASS="para">If you omit the <CODECLASS="literal">in</CODE><CODECLASS="replaceable"><I> list</I></CODE>, the loop steps through the command-line arguments.It puts the first command-line argument in <EMCLASS="emphasis">arg</EM> (or whateverelse you choose to call the <SPANCLASS="link">shell variable (<ACLASS="linkend"HREF="ch06_08.htm"TITLE="Shell Variables ">6.8</A>)</SPAN>),then executes the commands from <CODECLASS="literal">do</CODE> to <CODECLASS="literal">done</CODE>.Then it puts the next command-line argument in <EMCLASS="emphasis">arg</EM>, does the loop...and so on... ending the loop after handling all the arguments.</P><PCLASS="para"><ACLASS="indexterm"NAME="AUTOID-51435"></A><ACLASS="indexterm"NAME="AUTOID-51438"></A><ACLASS="indexterm"NAME="AUTOID-51440"></A>For an example of a <EMCLASS="emphasis">for</EM> loop, let's hack on the<SPANCLASS="link"><EMCLASS="emphasis">zpg</EM> (<ACLASS="linkend"HREF="ch44_12.htm"TITLE="Trapping Exits Caused by Interrupts ">44.12</A>)</SPAN>script.</P><PCLASS="para"><TABLECLASS="screen.co"BORDER="1"><TR><THVALIGN="TOP"><PRECLASS="calloutlist"> <ACLASS="co"HREF="ch44_06.htm"TITLE="44.6 Pattern Matching in case Statements ">case</A> </PRE></TH><TDVALIGN="TOP"><PRECLASS="screen">#!/bin/sh# zpg - UNCOMPRESS FILE(S), DISPLAY WITH pg# Usage: zpg [pg options] file [...files]stat=1 # DEFAULT EXIT STATUS; RESET TO 0 BEFORE NORMAL EXITtemp=/tmp/zpg$$trap 'rm -f $temp; exit $stat' 0trap 'echo "`basename $0`: Ouch! Quitting early..." 1>&2' 1 2 15files= switches=for arg<ACLASS="indexterm"NAME="AUTOID-51448"></A>do case "$arg" in -*) switches="$switches $arg" ;; *) files="$files $arg" ;; esacdonecase "$files" in"") echo "Usage: `basename $0` [pg options] file [files]" 1>&2 ;;*) for file in $files do gzcat "$file" | pg $switches done stat=0 ;;esac</PRE></TD></TR></TABLE></P><PCLASS="para">We added a <EMCLASS="emphasis">for</EM> loop to get and check each command-line argument.For example, let's say that a user typed:</P><PCLASS="para"><BLOCKQUOTECLASS="screen"><PRECLASS="screen">% <CODECLASS="userinput"><B>zpg -n afile ../bfile</B></CODE></PRE></BLOCKQUOTE></P><PCLASS="para"><ACLASS="indexterm"NAME="AUTOID-51458"></A><ACLASS="indexterm"NAME="AUTOID-51461"></A>The first pass through the <EMCLASS="emphasis">for</EM> loop, <CODECLASS="literal">$arg</CODE> is <CODECLASS="literal">-n</CODE>.Because the argument starts with a minus sign (<CODECLASS="literal">-</CODE>),the <EMCLASS="emphasis">case</EM> treats it as an option.Now the <CODECLASS="literal">switches</CODE> variable is replaced by its previous contents(an empty string), a space, and <CODECLASS="literal">-n</CODE>.Control goes to the <CODECLASS="literal">esac</CODE> and the loop repeatswith the next argument.</P><PCLASS="para">The next argument, <CODECLASS="literal">afile</CODE>, doesn't look like an option.So now the <CODECLASS="literal">files</CODE> variable will contain a space and <CODECLASS="literal">afile</CODE>.</P><PCLASS="para">The loop starts over once more, with <CODECLASS="literal">../bfile</CODE> in <CODECLASS="literal">$arg</CODE>.Again, this looks like a file, so now <CODECLASS="literal">$files</CODE> has<CODECLASS="literal"> afile ../bfile</CODE>.Because <CODECLASS="literal">../bfile</CODE> was the last argument, the loop ends;<CODECLASS="literal">$switches</CODE>has the options and <CODECLASS="literal">$files</CODE> has all the other arguments.</P><PCLASS="para">Next, we added another <EMCLASS="emphasis">for</EM> loop.This one has the word <CODECLASS="literal">in</CODE> followed by <CODECLASS="literal">$files</CODE>,so the loop steps through the contents of <CODECLASS="literal">$files</CODE>.The loop runs <EMCLASS="emphasis">gzcat</EM> on each file, piping it to <EMCLASS="emphasis">pg</EM> with any switchesyou gave.</P><PCLASS="para">Note that <CODECLASS="literal">$switches</CODE> isn't<SPANCLASS="link">quoted (<ACLASS="linkend"HREF="ch08_14.htm"TITLE="Bourne Shell Quoting ">8.14</A>)</SPAN>.This way, if <CODECLASS="literal">$switches</CODE> is empty, the shell won't pass an emptyargument to <EMCLASS="emphasis">pg</EM>.Also, if <CODECLASS="literal">$switches</CODE> has more than one switch, the shell will break theswitches into separate arguments at the spaces and pass them individually to<EMCLASS="emphasis">pg</EM>.</P><PCLASS="para"><ACLASS="indexterm"NAME="AUTOID-51499"></A><ACLASS="indexterm"NAME="AUTOID-51502"></A><ACLASS="indexterm"NAME="AUTOID-51505"></A><ACLASS="indexterm"NAME="AUTOID-51508"></A>You can use a <EMCLASS="emphasis">for</EM> loop with any space-separated (actually,<SPANCLASS="link">IFS (<ACLASS="linkend"HREF="ch35_21.htm"TITLE="Using IFS to Split Strings ">35.21</A>)</SPAN>-separated)list of words - not just filenames.You don't have to use a shell variable as the list;you can use<SPANCLASS="link">command substitution (<ACLASS="linkend"HREF="ch09_16.htm"TITLE="Command Substitution ">9.16</A>)</SPAN>(backquotes),<SPANCLASS="link">shell wildcards (<ACLASS="linkend"HREF="ch15_02.htm"TITLE="Filename Wildcards in a Nutshell ">15.2</A>)</SPAN>,or just "hardcode" the list of words:</P><PCLASS="para"><TABLECLASS="screen.co"BORDER="1"><TR><THVALIGN="TOP"><PRECLASS="calloutlist"> <ACLASS="co"HREF="ch13_13.htm"TITLE='13.13 The "Filename" - '>-</A> <ACLASS="co"HREF="ch43_02.htm"TITLE="43.2 Introduction to Printing on UNIX ">lpr</A> </PRE></TH><TDVALIGN="TOP"><PRECLASS="screen">for person in Joe Leslie Edie Allan<ACLASS="indexterm"NAME="AUTOID-51517"></A>do echo "Dear $person," | cat - form_letter | lprdone</PRE></TD></TR></TABLE></P><PCLASS="para"><ACLASS="indexterm"NAME="AUTOID-51523"></A><ACLASS="indexterm"NAME="UPT-ART-4940-IX-GETOPTS-COMMAND"></A>The<SPANCLASS="link"><EMCLASS="emphasis">getopt</EM> and <EMCLASS="emphasis">getopts</EM> (<ACLASS="linkend"HREF="ch44_18.htm"TITLE="Standard Command-Line Parsing ">44.18</A>)</SPAN>commands handle command-line arguments in a more standard way than<EMCLASS="emphasis">for</EM> loops.</P><DIVCLASS="sect1info"><PCLASS="SECT1INFO">- <SPANCLASS="authorinitials">JP</SPAN></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="515"TITLE="footer"><TABLEWIDTH="515"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="172"><ACLASS="SECT1"HREF="ch44_15.htm"TITLE="44.15 Handling Command-Line Arguments in Shell Scripts "><IMGSRC="gifs/txtpreva.gif"SRC="gifs/txtpreva.gif"ALT="Previous: 44.15 Handling Command-Line Arguments in Shell Scripts "BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="171"><ACLASS="book"HREF="index.htm"TITLE="UNIX Power Tools"><IMGSRC="gifs/txthome.gif"SRC="gifs/txthome.gif"ALT="UNIX Power Tools"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="172"><ACLASS="SECT1"HREF="ch44_17.htm"TITLE="44.17 Handling Arguments with while and shift "><IMGSRC="gifs/txtnexta.gif"SRC="gifs/txtnexta.gif"ALT="Next: 44.17 Handling Arguments with while and shift "BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="172">44.15 Handling Command-Line Arguments in Shell Scripts </TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="171"><ACLASS="index"HREF="index/idx_0.htm"TITLE="Book Index"><IMGSRC="gifs/index.gif"SRC="gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="172">44.17 Handling Arguments with while and shift </TD></TR></TABLE><HRALIGN="LEFT"WIDTH="515"TITLE="footer"><IMGSRC="gifs/smnavbar.gif"SRC="gifs/smnavbar.gif"USEMAP="#map"BORDER="0"ALT="The UNIX CD Bookshelf Navigation"><MAPNAME="map"><AREASHAPE="RECT"COORDS="0,0,73,21"HREF="../index.htm"ALT="The UNIX CD Bookshelf"><AREASHAPE="RECT"COORDS="74,0,163,21"HREF="index.htm"ALT="UNIX Power Tools"><AREASHAPE="RECT"COORDS="164,0,257,21"HREF="../unixnut/index.htm"ALT="UNIX in a Nutshell"><AREASHAPE="RECT"COORDS="258,0,321,21"HREF="../vi/index.htm"ALT="Learning the vi Editor"><AREASHAPE="RECT"COORDS="322,0,378,21"HREF="../sedawk/index.htm"ALT="sed & awk"><AREASHAPE="RECT"COORDS="379,0,438,21"HREF="../ksh/index.htm"ALT="Learning the Korn Shell"><AREASHAPE="RECT"COORDS="439,0,514,21"HREF="../lrnunix/index.htm"ALT="Learning the UNIX Operating System"></MAP></DIV></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -