Shell: Update section on input validation

Also mention safety of [[ $var =~ regexp ]].
This commit is contained in:
Florian Weimer 2014-10-10 16:44:53 +02:00
parent 01cf74aac0
commit e23c383775

View file

@ -162,6 +162,14 @@ external-program "$arg1" "$arg2"
evaluation, even with integer operators such as evaluation, even with integer operators such as
<literal>-eq</literal>.) <literal>-eq</literal>.)
</para> </para>
<para>
The conditional expression
<literal>[[ $</literal><emphasis>variable</emphasis><literal> =~ </literal><emphasis>regexp</emphasis><literal> ]]</literal>
can be used for input validation, assuming that
<emphasis>regexp</emphasis> is a constant regular
expression.
See <xref linkend="sect-Defensive_Coding-Shell-Input_Validation"/>.
</para>
</listitem> </listitem>
<listitem> <listitem>
<para> <para>
@ -391,29 +399,27 @@ trap cleanup 0
</para> </para>
<para> <para>
The following construct can be used to check if a string The following construct can be used to check if a string
<literal>$value</literal>” is not a non-negative integer. <literal>$value</literal>” is an integer.
</para> </para>
<informalexample> <informalexample>
<programlisting language="Bash"> <programlisting language="Bash">
case "$value" in if [[ $value =~ ^-?[0-9]$ ]] ; then
*[!0-9]*) echo value is an integer
echo "invalid input value" 1>&amp;2 else
exit 1 echo "value is not an integer" 1>&amp;2
;; exit 1
esac fi
</programlisting> </programlisting>
</informalexample> </informalexample>
<para> <para>
The pattern “<literal>*[!0-9]*</literal>” is not special shell Using <literal>case</literal> statements for input validation is
syntax—it matches any string which contains arbitrary characters, also possible, but the pattern language is more restrictive, and
followed by a non-digit, followed by arbitrary characters. it can be difficult to write suitable patterns.
</para> </para>
<para> <para>
Using <literal>case</literal> statements is the most reliable way The <literal>expr</literal> external command can give misleading
for performing input validation, although constructing proper results (e.g., if the value being checked contains operators
patterns is difficult. The <literal>expr</literal> external itself) and should not be used.
command and the built-in operator <literal>=~</literal> can give
misleading results.
</para> </para>
</section> </section>
<section id="sect-Defensive_Coding-Shell-Edit_Guard"> <section id="sect-Defensive_Coding-Shell-Edit_Guard">