将整数作为字符串添加到变量bash中 [英] Add integers as strings to a variable bash
问题描述
我想通过向变量添加随机整数来输出字符串来创建字符串。然而,Bash只是将数字加在一起。
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}
假设每个随机数为1,脚本将输出3,而不是111.
如何达到111的预期结果?
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:
let b+=$number
运行帮助让
:
let: let ARGUMENT...
Evaluate arithmetic expressions.
这解释了为什么让b + = $ number
执行整数加法( 1
, 2
, 3
) $ number
到 b
而不是字符串连接。
That explains why let b+=$number
performs an integer addition (1
, 2
, 3
) of $number
to b
instead of string concatenation.
只需删除让
和所需行为 1
, 11
, 111
将会发生。
Simply remove let
and the desired behavior 1
, 11
, 111
will occur.
执行字符串连接的另一种方法:
The other method to perform string concatenation:
b="$b$number"
是的,只需让 b
成为连接 b
和数字的结果
。
Yes, simply "let b
become the result of concatenating b
and number
.
作为附注, b =
相当于 b =
as 扩展为空字符串。对变量的模块操作可以通过算术扩展完成:
number = $((RANDOM%9))
。
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))
.
这篇关于将整数作为字符串添加到变量bash中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!