I'm having trouble saving an asterisk to a variable within a Bash script. The inputs I use are -1 and 1.
#!/bin/bash
function aleatorio {
printf "((%d %% 1000) / 1000,0) * (%f - %f) + %f\n" $RANDOM $2 $1 $1
}
X=`aleatorio -1 1`
echo $X
When I print the variable $X
, that asterisk is replaced by all the elements of the current route. I've also tried single quotes.
The output I get when running the program is:
((12210 % 1000) / 1000,0) CarloMagno.sh Downloads Documents git.txt Images Practice_03_AC Practice_03_IA Practice_04_FIS Programming ProgramasPortables Test.sh scriptVectorNUltraDimensional.sh TasksPending.txt University (1,000000 - -1,000000) + -1,000000
Those are the elements that are in the folder where I execute the Script. That happens both using double quotes, and single quotes, like \*
After editing the question I have noticed that you can solve this mathematical calculation with the tool
bc
that supports decimal operations (unlike the arithmetic expansion operator$(( ... ))
that works only with integers).This modification to your code would make it work correctly:
On the one hand I pass
bc
the expression to solve it and on the other hand I indicateprintf
that it does not use "localized" decimals (with commas,
instead of points.
in the decimal separator) so thatbc
it does not complain about it.It could also have been used
echo
to avoid us usingLANG=C
inprintf
:The solution explained when we tried to explain how to display a variable containing an asterisk without the asterisk being interpreted is here .
Bash is not the best language for dealing with arithmetic expressions that require floating point. If you want to use something clean and fast, use Awk!
In the context of a script you could do:
As you can see, we pass the variables to Awk using
-v variable="$variable_en_bash"
.If you had an arithmetic expression without floating point, you could execute it with
$(( expresión ))
:This is explained in Bash Reference Manual → 3.5.5 Arithmetic Expansion
But why
*
is it expanding to the list of files in your path?In Bash,
*
it has a special value that, depending on the context, expands the list of files and possible directories and subdirectories from the point where you are.The same goes for
?
, which matches a character.So if you want to print an asterisk, you must either enclose it in quotes or escape it:
You have more information in Bash Reference Manual → 3.5.8.1 Pattern Matching , where you can see that for example you can disable the option:
Have you tried using
\
? Since it is the character escape mark.