Add integers as strings to a variable bash
bash, int, string
Solution
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))`.
Problem
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?