Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add integers as strings to a variable bash

Tags:

string

bash

int

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?

like image 440
Matt R Avatar asked May 06 '12 21:05

Matt R


People also ask

How do I append a string to a variable in bash?

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

What does %% mean in bash?

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.


1 Answers

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

like image 117
Lekensteyn Avatar answered Sep 29 '22 14:09

Lekensteyn