15

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?

1 Answer 1

31

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)).

Sign up to request clarification or add additional context in comments.

1 Comment

You can also do arithmetic expansion like this: ((number = RANDOM % 9))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.