📄 tests.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>Tests</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Basics"HREF="part2.html"><LINKREL="PREVIOUS"TITLE="Exit and Exit Status"HREF="exit-status.html"><LINKREL="NEXT"TITLE="File test operators"HREF="fto.html"><METAHTTP-EQUIV="Content-Style-Type"CONTENT="text/css"><LINKREL="stylesheet"HREF="common/kde-common.css"TYPE="text/css"><METAHTTP-EQUIV="Content-Type"CONTENT="text/html; charset=iso-8859-1"><METAHTTP-EQUIV="Content-Language"CONTENT="en"><LINKREL="stylesheet"HREF="common/kde-localised.css"TYPE="text/css"TITLE="KDE-English"><LINKREL="stylesheet"HREF="common/kde-default.css"TYPE="text/css"TITLE="KDE-Default"></HEAD><BODYCLASS="CHAPTER"BGCOLOR="#FFFFFF"TEXT="#000000"LINK="#AA0000"VLINK="#AA0055"ALINK="#AA0000"STYLE="font-family: sans-serif;"><DIVCLASS="NAVHEADER"><TABLESUMMARY="Header navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><THCOLSPAN="3"ALIGN="center">Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH></TR><TR><TDWIDTH="10%"ALIGN="left"VALIGN="bottom"><AHREF="exit-status.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom"></TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="fto.html"ACCESSKEY="N">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="CHAPTER"><H1><ANAME="TESTS"></A>Chapter 7. Tests</H1><P><ANAME="IFTHEN"></A></P><P>Every reasonably complete programming language can test for a condition, then act according to the result of the test. Bash has the <AHREF="tests.html#TTESTREF">test</A> command, various bracket and parenthesis operators, and the <BCLASS="COMMAND">if/then</B> construct.</P><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="TESTCONSTRUCTS"></A>7.1. Test Constructs</H1><P><ANAME="TESTCONSTRUCTS1"></A></P><UL><LI><P>An <BCLASS="COMMAND">if/then</B> construct tests whether the <AHREF="exit-status.html#EXITSTATUSREF">exit status</A> of a list of commands is <SPANCLASS="RETURNVALUE">0</SPAN> (since 0 means <SPANCLASS="QUOTE">"success"</SPAN> by UNIX convention), and if so, executes one or more commands.</P></LI><LI><P>There exists a dedicated command called <BCLASS="COMMAND"> [</B> (<AHREF="special-chars.html#LEFTBRACKET">left bracket</A> special character). It is a synonym for <BCLASS="COMMAND">test</B>, and a <AHREF="internal.html#BUILTINREF">builtin</A> for efficiency reasons. This command considers its arguments as comparison expressions or file tests and returns an exit status corresponding to the result of the comparison (0 for true, 1 for false).</P></LI><LI><P>With version 2.02, Bash introduced the <AHREF="tests.html#DBLBRACKETS">[[ ... ]]</A> <ICLASS="FIRSTTERM">extended test command</I>, which performs comparisons in a manner more familiar to programmers from other languages. Note that <BCLASS="COMMAND">[[</B> is a <AHREF="internal.html#KEYWORDREF">keyword</A>, not a command.</P><P>Bash sees <TTCLASS="USERINPUT"><B>[[ $a -lt $b ]]</B></TT> as a single element, which returns an exit status.</P><P>The <AHREF="dblparens.html">(( ... ))</A> and <AHREF="internal.html#LETREF">let ...</A> constructs also return an exit status of <SPANCLASS="RETURNVALUE">0</SPAN> if the arithmetic expressions they evaluate expand to a non-zero value. These <AHREF="arithexp.html#ARITHEXPREF">arithmetic expansion</A> constructs may therefore be used to perform arithmetic comparisons. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 let "1<2" returns 0 (as "1<2" expands to "1") 2 (( 0 && 1 )) returns 1 (as "0 && 1" expands to "0")</PRE></TD></TR></TABLE> </P></LI><LI><P><ANAME="IFGREPREF"></A></P><P>An <BCLASS="COMMAND">if</B> can test any command, not just conditions enclosed within brackets. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 if cmp a b &> /dev/null # Suppress output. 2 then echo "Files a and b are identical." 3 else echo "Files a and b differ." 4 fi 5 6 # The very useful "if-grep" construct: 7 # ----------------------------------- 8 if grep -q Bash file 9 then echo "File contains at least one occurrence of Bash." 10 fi 11 12 word=Linux 13 letter_sequence=inu 14 if echo "$word" | grep -q "$letter_sequence" 15 # The "-q" option to grep suppresses output. 16 then 17 echo "$letter_sequence found in $word" 18 else 19 echo "$letter_sequence not found in $word" 20 fi 21 22 23 if COMMAND_WHOSE_EXIT_STATUS_IS_0_UNLESS_ERROR_OCCURRED 24 then echo "Command succeeded." 25 else echo "Command failed." 26 fi</PRE></TD></TR></TABLE> </P></LI><LI><P>An <BCLASS="COMMAND">if/then</B> construct can contain nested comparisons and tests. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 if echo "Next *if* is part of the comparison for the first *if*." 2 3 if [[ $comparison = "integer" ]] 4 then (( a < b )) 5 else 6 [[ $a < $b ]] 7 fi 8 9 then 10 echo '$a is less than $b' 11 fi</PRE></TD></TR></TABLE> </P><P><SPANCLASS="emphasis"><ICLASS="EMPHASIS">This detailed <SPANCLASS="QUOTE">"if-test"</SPAN> explanation courtesy of St閜hane Chazelas.</I></SPAN></P></LI></UL><DIVCLASS="EXAMPLE"><HR><ANAME="EX10"></A><P><B>Example 7-1. What is truth?</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 3 # Tip: 4 # If you're unsure of how a certain condition would evaluate, 5 #+ test it in an if-test. 6 7 echo 8 9 echo "Testing \"0\"" 10 if [ 0 ] # zero 11 then 12 echo "0 is true." 13 else 14 echo "0 is false." 15 fi # 0 is true. 16 17 echo 18 19 echo "Testing \"1\"" 20 if [ 1 ] # one 21 then 22 echo "1 is true." 23 else 24 echo "1 is false." 25 fi # 1 is true. 26 27 echo 28 29 echo "Testing \"-1\"" 30 if [ -1 ] # minus one 31 then 32 echo "-1 is true." 33 else 34 echo "-1 is false." 35 fi # -1 is true. 36 37 echo 38 39 echo "Testing \"NULL\"" 40 if [ ] # NULL (empty condition) 41 then 42 echo "NULL is true." 43 else 44 echo "NULL is false." 45 fi # NULL is false. 46 47 echo 48 49 echo "Testing \"xyz\"" 50 if [ xyz ] # string 51 then 52 echo "Random string is true." 53 else 54 echo "Random string is false." 55 fi # Random string is true. 56 57 echo 58 59 echo "Testing \"\$xyz\"" 60 if [ $xyz ] # Tests if $xyz is null, but... 61 # it's only an uninitialized variable. 62 then 63 echo "Uninitialized variable is true." 64 else 65 echo "Uninitialized variable is false." 66 fi # Uninitialized variable is false. 67 68 echo 69 70 echo "Testing \"-n \$xyz\"" 71 if [ -n "$xyz" ] # More pedantically correct. 72 then 73 echo "Uninitialized variable is true." 74 else 75 echo "Uninitialized variable is false." 76 fi # Uninitialized variable is false. 77 78 echo 79 80 81 xyz= # Initialized, but set to null value. 82 83 echo "Testing \"-n \$xyz\"" 84 if [ -n "$xyz" ] 85 then 86 echo "Null variable is true." 87 else 88 echo "Null variable is false." 89 fi # Null variable is false. 90 91 92 echo 93 94 95 # When is "false" true? 96 97 echo "Testing \"false\"" 98 if [ "false" ] # It seems that "false" is just a string. 99 then 100 echo "\"false\" is true." #+ and it tests true. 101 else 102 echo "\"false\" is false." 103 fi # "false" is true. 104 105 echo 106 107 echo "Testing \"\$false\"" # Again, uninitialized variable. 108 if [ "$false" ] 109 then 110 echo "\"\$false\" is true." 111 else 112 echo "\"\$false\" is false." 113 fi # "$false" is false. 114 # Now, we get the expected result. 115 116 # What would happen if we tested the uninitialized variable "$true"? 117 118 echo 119 120 exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="FORMALPARA"><P><B>Exercise. </B>Explain the behavior of <AHREF="tests.html#EX10">Example 7-1</A>, above.</P></DIV><P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 if [ condition-true ] 2 then 3 command 1 4 command 2 5 ... 6 else 7 # Optional (may be left out if not needed). 8 # Adds default code block executing if original condition tests false. 9 command 3 10 command 4 11 ... 12 fi</PRE></TD></TR></TABLE> </P><DIVCLASS="NOTE"><TABLECLASS="NOTE"WIDTH="100%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/note.png"HSPACE="5"ALT="Note"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>When <ICLASS="FIRSTTERM">if</I> and <ICLASS="FIRSTTERM">then</I> are on same line in a condition test, a semicolon must terminate the <ICLASS="FIRSTTERM">if</I> statement. Both <ICLASS="FIRSTTERM">if</I> and <ICLASS="FIRSTTERM">then</I> are <AHREF="internal.html#KEYWORDREF">keywords</A>. Keywords (or commands) begin statements, and before a new statement on the same line begins, the old one must terminate.</P><P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 if [ -x "$filename" ]; then</PRE></TD></TR></TABLE></P></TD></TR></TABLE></DIV><DIVCLASS="VARIABLELIST"><P><B><ANAME="ELIFREF1"></A>Else if and elif</B></P><DL><DT><SPANCLASS="TOKEN">elif</SPAN></DT><DD><P><TTCLASS="USERINPUT"><B>elif</B></TT> is a contraction for <SPANCLASS="TOKEN">else if</SPAN>. The effect is to nest an inner <SPANCLASS="TOKEN">if/then</SPAN> construct within an outer one.</P><P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 if [ condition1 ] 2 then 3 command1 4 command2 5 command3 6 elif [ condition2 ] 7 # Same as else if 8 then 9 command4 10 command5 11 else 12 default-command 13 fi</PRE></TD></TR></TABLE> </P></DD></DL></DIV><P>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -