I want to output a string by adding random integer to a variable to create the string. Bash however, just adds the numbers together.
#!/bin/bash
b=""
for ((x=1; x<=3; x++))
do
number=$RANDOM
let number%=9
let b+=$number
done
echo ${b}
Say every random number is 1, the script will output 3 instead of 111. How do I achieve the desired result of 111?
As of Bash version 3.1, a second method can be used to concatenate strings by using the += operator. The operator is generally used to append numbers and strings, and other variables to an existing variable. In this method, the += is essentially shorthand for saying "add this to my existing variable".
The operator "%" will try to remove the shortest text matching the pattern, while "%%" tries to do it with the longest text matching. Follow this answer to receive notifications.
There are several possibilities to achieve your desired behavior. Let's first examine what you've done:
let b+=$number
Running help let
:
let: let ARGUMENT...
Evaluate arithmetic expressions.
That explains why let b+=$number
performs an integer addition (1
, 2
, 3
) of $number
to b
instead of string concatenation.
Simply remove let
and the desired behavior 1
, 11
, 111
will occur.
The other method to perform string concatenation:
b="$b$number"
Yes, simply "let b
become the result of concatenating b
and number
.
As a side note, b=""
is equivalent to b=
as ""
is expanded to an empty string. Module operation on a variable can be done with arithmetic expansion: number=$((RANDOM%9))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With