2 SC2304
Vidar Holen edited this page 2021-08-22 20:05:48 -07:00
This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

* must be escaped to multiply: \*. Modern $((x * y)) avoids this issue.

Problematic code:

result=$(expr 2 * 3)

Correct code:

# Modern, efficient, POSIX standard approach
result=$(( 2 * 3 ))

# Older, slower approach
result=$(expr 2 \* 3)

Rationale:

ShellCheck found an expr command whose operator is an unescaped asterisk *.

When using expr, each argument is expanded the same way as for any other command. This means that expr 2 * 3 will turn into expr 2 Desktop Documents Downloads Music Pictures 3 depending on the files in the current directory, causing an error like expr: syntax error: unexpected argument Desktop

The best way to avoid this is to avoid expr and instead use $((..)) instead. If you for any reason prefer the 200x slower, heavyweight process of forking a new process, you can escape the *. Both ways are demonstrated in the correct example.

Exceptions:

None

  • Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!