⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 parameter-substitution.html

📁 Shall高级编程
💻 HTML
📖 第 1 页 / 共 3 页
字号:
  47&nbsp;#  Compare these methods of checking whether a variable has been set  48&nbsp;#+ with "set -u" . . .  49&nbsp;  50&nbsp;  51&nbsp;  52&nbsp;echo "You will not see this message, because script already terminated."  53&nbsp;  54&nbsp;HERE=0  55&nbsp;exit $HERE   # Will NOT exit here.  56&nbsp;  57&nbsp;# In fact, this script will return an exit status (echo $?) of 1.</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="USAGEMESSAGE"></A><P><B>Example 9-17. Parameter substitution and <SPANCLASS="QUOTE">"usage"</SPAN> messages</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# usage-message.sh   3&nbsp;   4&nbsp;: ${1?"Usage: $0 ARGUMENT"}   5&nbsp;#  Script exits here if command-line parameter absent,   6&nbsp;#+ with following error message.   7&nbsp;#    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT   8&nbsp;   9&nbsp;echo "These two lines echo only if command-line parameter given."  10&nbsp;echo "command line parameter = \"$1\""  11&nbsp;  12&nbsp;exit 0  # Will exit here only if command-line parameter present.  13&nbsp;  14&nbsp;# Check the exit status, both with and without command-line parameter.  15&nbsp;# If command-line parameter present, then "$?" is 0.  16&nbsp;# If not, then "$?" is 1.</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="FORMALPARA"><P><B>Parameter substitution and/or expansion. </B><ANAME="PSUB2"></A>The following expressions are		the complement to the <BCLASS="COMMAND">match</B>		<TTCLASS="REPLACEABLE"><I>in</I></TT> <BCLASS="COMMAND">expr</B>		string operations (see <AHREF="moreadv.html#EX45">Example 15-9</A>).		These particular ones are used mostly in parsing file		path names.</P></DIV><DIVCLASS="VARIABLELIST"><P><B><ANAME="PSOREX1"></A>Variable length / Substring removal</B></P><DL><DT><TTCLASS="USERINPUT"><B>${#var}</B></TT></DT><DD><P><TTCLASS="USERINPUT"><B>String length</B></TT> (number		    of characters in <TTCLASS="VARNAME">$var</TT>). For		    an <AHREF="arrays.html#ARRAYREF">array</A>,		    <BCLASS="COMMAND">${#array}</B> is the length of the		    first element in the array.</P><DIVCLASS="NOTE"><TABLECLASS="NOTE"WIDTH="90%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/note.png"HSPACE="5"ALT="Note"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>		    Exceptions:		  <UL><LI><P><ANAME="NUMPOSPARAM"></A></P><P>		      <BCLASS="COMMAND">${#*}</B> and		      <BCLASS="COMMAND">${#@}</B> give the <SPANCLASS="emphasis"><ICLASS="EMPHASIS">number		      of positional parameters</I></SPAN>.		    </P></LI><LI><P>		      For an array, <BCLASS="COMMAND">${#array[*]}</B> and		      <BCLASS="COMMAND">${#array[@]}</B> give the number		      of elements in the array.		    </P></LI></UL>		  </P></TD></TR></TABLE></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="LENGTH"></A><P><B>Example 9-18. Length of a variable</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# length.sh   3&nbsp;   4&nbsp;E_NO_ARGS=65   5&nbsp;   6&nbsp;if [ $# -eq 0 ]  # Must have command-line args to demo script.   7&nbsp;then   8&nbsp;  echo "Please invoke this script with one or more command-line arguments."   9&nbsp;  exit $E_NO_ARGS  10&nbsp;fi    11&nbsp;  12&nbsp;var01=abcdEFGH28ij  13&nbsp;echo "var01 = ${var01}"  14&nbsp;echo "Length of var01 = ${#var01}"  15&nbsp;# Now, let's try embedding a space.  16&nbsp;var02="abcd EFGH28ij"  17&nbsp;echo "var02 = ${var02}"  18&nbsp;echo "Length of var02 = ${#var02}"  19&nbsp;  20&nbsp;echo "Number of command-line arguments passed to script = ${#@}"  21&nbsp;echo "Number of command-line arguments passed to script = ${#*}"  22&nbsp;  23&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV></DD><DT><ANAME="PSOREX2"></A><TTCLASS="USERINPUT"><B>${var#Pattern}</B></TT>, <TTCLASS="USERINPUT"><B>${var##Pattern}</B></TT></DT><DD><P><ANAME="PSOREXSH"></A></P><P><BCLASS="COMMAND">${var#Pattern} </B>		  Remove from <TTCLASS="VARNAME">$var</TT>		  the <SPANCLASS="emphasis"><ICLASS="EMPHASIS">shortest</I></SPAN> part of		  <TTCLASS="VARNAME">$Pattern</TT> that matches		  the <TTCLASS="REPLACEABLE"><I>front end</I></TT> of		  <TTCLASS="VARNAME">$var</TT>.		</P><P><ANAME="PSOREXLO"></A></P><P><BCLASS="COMMAND">${var##Pattern} </B>		  Remove from <TTCLASS="VARNAME">$var</TT>		  the <SPANCLASS="emphasis"><ICLASS="EMPHASIS">longest</I></SPAN> part of		  <TTCLASS="VARNAME">$Pattern</TT> that matches		  the <TTCLASS="REPLACEABLE"><I>front end</I></TT> of		  <TTCLASS="VARNAME">$var</TT>.		</P><P>A usage illustration from <AHREF="contributed-scripts.html#DAYSBETWEEN">Example A-7</A>:<TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;# Function from "days-between.sh" example.  # Strips   2&nbsp;leading zero(s) from argument passed.   3&nbsp;   4&nbsp;strip_leading_zero () #  Strip possible leading zero(s)   5&nbsp;{                     #+ from argument passed.   6&nbsp;  return=${1#0}       #  The "1" refers to "$1" -- passed arg.   7&nbsp;}                     #  The "0" is what to remove from "$1" -- strips zeros.</PRE></TD></TR></TABLE>		</P><P>Manfred Schwarb's more elaborate variation of the above:<TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;strip_leading_zero2 () # Strip possible leading zero(s), since otherwise   2&nbsp;{                      # Bash will interpret such numbers as octal values.   3&nbsp;  shopt -s extglob     # Turn on extended globbing.   4&nbsp;  local val=${1##+(0)} # Use local variable, longest matching series of 0's.   5&nbsp;  shopt -u extglob     # Turn off extended globbing.   6&nbsp;  _strip_leading_zero2=${val:-0}   7&nbsp;                       # If input was 0, return 0 instead of "".   8&nbsp;}</PRE></TD></TR></TABLE>		</P><P>Another usage illustration: <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;echo `basename $PWD`        # Basename of current working directory.   2&nbsp;echo "${PWD##*/}"           # Basename of current working directory.   3&nbsp;echo   4&nbsp;echo `basename $0`          # Name of script.   5&nbsp;echo $0                     # Name of script.   6&nbsp;echo "${0##*/}"             # Name of script.   7&nbsp;echo   8&nbsp;filename=test.data   9&nbsp;echo "${filename##*.}"      # data  10&nbsp;                            # Extension of filename.</PRE></TD></TR></TABLE>		</P></DD><DT><ANAME="PCTPATREF"></A><TTCLASS="USERINPUT"><B>${var%Pattern}</B></TT>, <TTCLASS="USERINPUT"><B>${var%%Pattern}</B></TT></DT><DD><P><ANAME="PCTREP1"></A></P><P><BCLASS="COMMAND">{$var%Pattern}</B>		  Remove from <TTCLASS="VARNAME">$var</TT>		  the <SPANCLASS="emphasis"><ICLASS="EMPHASIS">shortest</I></SPAN> part of		  <TTCLASS="VARNAME">$Pattern</TT> that matches		  the <TTCLASS="REPLACEABLE"><I>back end</I></TT> of		  <TTCLASS="VARNAME">$var</TT>.  </P><P><ANAME="PCTREP2"></A></P><P><BCLASS="COMMAND">{$var%%Pattern}</B>		  Remove from <TTCLASS="VARNAME">$var</TT>		  the <SPANCLASS="emphasis"><ICLASS="EMPHASIS">longest</I></SPAN> part of		  <TTCLASS="VARNAME">$Pattern</TT> that matches		  the <TTCLASS="REPLACEABLE"><I>back end</I></TT> of		  <TTCLASS="VARNAME">$var</TT>.  </P></DD></DL></DIV><P><AHREF="bash2.html#BASH2REF">Version 2</A> of Bash added	      additional options.</P><DIVCLASS="EXAMPLE"><HR><ANAME="PATTMATCHING"></A><P><B>Example 9-19. Pattern matching in parameter substitution</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# patt-matching.sh   3&nbsp;   4&nbsp;# Pattern matching  using the # ## % %% parameter substitution operators.   5&nbsp;   6&nbsp;var1=abcd12345abc6789   7&nbsp;pattern1=a*c  # * (wild card) matches everything between a - c.   8&nbsp;   9&nbsp;echo  10&nbsp;echo "var1 = $var1"           # abcd12345abc6789  11&nbsp;echo "var1 = ${var1}"         # abcd12345abc6789  12&nbsp;                              # (alternate form)  13&nbsp;echo "Number of characters in ${var1} = ${#var1}"  14&nbsp;echo  15&nbsp;  16&nbsp;echo "pattern1 = $pattern1"   # a*c  (everything between 'a' and 'c')  17&nbsp;echo "--------------"  18&nbsp;echo '${var1#$pattern1}  =' "${var1#$pattern1}"    #         d12345abc6789  19&nbsp;# Shortest possible match, strips out first 3 characters  abcd12345abc6789  20&nbsp;#                                     ^^^^^               |-|  21&nbsp;echo '${var1##$pattern1} =' "${var1##$pattern1}"   #                  6789        22&nbsp;# Longest possible match, strips out first 12 characters  abcd12345abc6789  23&nbsp;#                                    ^^^^^                |----------|  24&nbsp;  25&nbsp;echo; echo; echo  26&nbsp;  27&nbsp;pattern2=b*9            # everything between 'b' and '9'  28&nbsp;echo "var1 = $var1"     # Still  abcd12345abc6789  29&nbsp;echo  30&nbsp;echo "pattern2 = $pattern2"  31&nbsp;echo "--------------"  32&nbsp;echo '${var1%pattern2}  =' "${var1%$pattern2}"     #     abcd12345a  33&nbsp;# Shortest possible match, strips out last 6 characters  abcd12345abc6789  34&nbsp;#                                     ^^^^                         |----|  35&nbsp;echo '${var1%%pattern2} =' "${var1%%$pattern2}"    #     a  36&nbsp;# Longest possible match, strips out last 12 characters  abcd12345abc6789  37&nbsp;#                                    ^^^^                 |-------------|  38&nbsp;  39&nbsp;# Remember, # and ## work from the left end (beginning) of string,  40&nbsp;#           % and %% work from the right end.  41&nbsp;  42&nbsp;echo  43&nbsp;  44&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="RFE"></A><P><B>Example 9-20. Renaming file extensions<SPANCLASS="TOKEN">:</SPAN></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# rfe.sh: Renaming file extensions.   3&nbsp;#   4&nbsp;#         rfe old_extension new_extension   5&nbsp;#   6&nbsp;# Example:   7&nbsp;# To rename all *.gif files in working directory to *.jpg,   8&nbsp;#          rfe gif jpg   9&nbsp;  10&nbsp;  11&nbsp;E_BADARGS=65

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -