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?
There are several possibilities to achieve your desired behavior. Let’s first examine what you’ve done:
Running
help let:That explains why
let b+=$numberperforms an integer addition (1,2,3) of$numbertobinstead of string concatenation.Simply remove
letand the desired behavior1,11,111will occur.The other method to perform string concatenation:
Yes, simply “let
bbecome the result of concatenatingbandnumber.As a side note,
b=""is equivalent tob=as""is expanded to an empty string. Module operation on a variable can be done with arithmetic expansion:number=$((RANDOM%9)).