From d0077342342ed836f1a3fa0a306504f64cc5d203 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 8 Feb 2014 15:25:23 -0800 Subject: [PATCH] Created SC2003 (markdown) --- SC2003.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 SC2003.md diff --git a/SC2003.md b/SC2003.md new file mode 100644 index 0000000..35efdf5 --- /dev/null +++ b/SC2003.md @@ -0,0 +1,25 @@ +# expr is antiquated. Consider rewriting this using $((..)), ${} or [[ ]]. + +### Problematic code: + + i=$(expr 1 + 2) + l=$(expr length "$var") + +### Correct code: + + i=$((1+2)) + l=${#var} + +### Rationale: + +[To quote POSIX:](http://pubs.opengroup.org/onlinepubs/009695399/utilities/expr.html) + +> The expr utility has a rather difficult syntax [...] In many cases, the arithmetic and string features provided as part of the shell command language are easier to use than their equivalents in expr. Newly written scripts should avoid expr in favor of the new features within the shell. + +### Contraindications + +`sh` doesn't have a great replacement for the `:` operator (regex match). ShellCheck tries not to warn when using expr with `:`, but e.g. `op=:; expr string "$op" regex` still trigger it. + +Other than that, all uses of `expr` can be rewritten to use modern shell features instead. + +Bash has `[[ string =~ regex ]]`, so not even `expr .. : ..` is necessary. \ No newline at end of file