From e23c38377538e4c9f0311347b6fc15b8c1dddd37 Mon Sep 17 00:00:00 2001 From: Florian Weimer Date: Fri, 10 Oct 2014 16:44:53 +0200 Subject: [PATCH] Shell: Update section on input validation Also mention safety of [[ $var =~ regexp ]]. --- defensive-coding/en-US/Shell.xml | 36 +++++++++++++++++++------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/defensive-coding/en-US/Shell.xml b/defensive-coding/en-US/Shell.xml index 24554b1..042ac61 100644 --- a/defensive-coding/en-US/Shell.xml +++ b/defensive-coding/en-US/Shell.xml @@ -162,6 +162,14 @@ external-program "$arg1" "$arg2" evaluation, even with integer operators such as -eq.) + + The conditional expression + “[[ $variable =~ regexp ]]” + can be used for input validation, assuming that + regexp is a constant regular + expression. + See . + @@ -391,29 +399,27 @@ trap cleanup 0 The following construct can be used to check if a string - “$value” is not a non-negative integer. + “$value” is an integer. -case "$value" in - *[!0-9]*) - echo "invalid input value" 1>&2 - exit 1 - ;; -esac +if [[ $value =~ ^-?[0-9]$ ]] ; then + echo value is an integer +else + echo "value is not an integer" 1>&2 + exit 1 +fi - The pattern “*[!0-9]*” is not special shell - syntax—it matches any string which contains arbitrary characters, - followed by a non-digit, followed by arbitrary characters. + Using case statements for input validation is + also possible, but the pattern language is more restrictive, and + it can be difficult to write suitable patterns. - Using case statements is the most reliable way - for performing input validation, although constructing proper - patterns is difficult. The expr external - command and the built-in operator =~ can give - misleading results. + The expr external command can give misleading + results (e.g., if the value being checked contains operators + itself) and should not be used.