Home > Blockchain >  Should * be escaped in bash when it is used inside double braces to perform multiplication?
Should * be escaped in bash when it is used inside double braces to perform multiplication?

Time:12-03

I thought * should be escaped in bash when it is to be used in a meaning other than the universal character, for example I am trying to use * to multiply two numbers. But when I am trying to use * with an escape character I am getting an error.

echo "scale=2; 10 \* 3" | bc

EOF encountered in a comment.
(standard_in) 1: syntax error

but when I am not using the escape character it works.

echo "scale=2; 10 * 3" | bc

30

why is this? Can someone explain?

CodePudding user response:

You would use \ to escape the *, not /, but no, you do not need to escape it. bash is not doing the multiplication; it's simply writing a string to the standard input of bc.

The double quotes already escape * from being interpreted by the shell.

echo "scale=2; 10 * 3"

is equivalent to

echo scale=2\;\ 10\ \*\ 3

Regarding the error message in your first attempt, bc scripts allow C-style comments, so /* was interpreted as the start of a comment that was never completed before the end of the script.

CodePudding user response:

In bash, the * character does not need to be escaped when it is used inside double braces for multiplication. This is because the * character is not treated as a wildcard inside double braces.

For example, the following command:

echo "scale=2; 10 * 3" | bc

Will output 30, because the * character is treated as a multiplication operator inside the double braces.

However, if you try to use the * character with an escape character, like this:

Copy code

echo "scale=2; 10 \* 3" | bc

You will get an error, because the escape character \ tells bash to treat the * character as a literal * and not as a multiplication operator. This causes a syntax error, because the * character is not a valid operator inside double braces.

In general, it is not necessary to escape the * character when using it inside double braces for multiplication. However, if you do want to use the * character as a literal * inside double braces, you can escape it with a backslash.

  • Related