string 将整数作为字符串添加到变量 bash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10474250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add integers as strings to a variable bash
提问by Matt R
I want to output a string by adding random integer to a variable to create the string. Bash however, just adds the numbers together.
我想通过将随机整数添加到变量来创建字符串来输出字符串。然而,Bash 只是将数字相加。
#!/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,脚本将输出 3 而不是 111。如何达到 111 的预期结果?
回答by Lekensteyn
There are several possibilities to achieve your desired behavior. Let's first examine what you've done:
有几种可能性可以实现您想要的行为。让我们首先检查你做了什么:
let b+=$number
Running help let
:
运行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.
这解释了为什么let b+=$number
执行to的整数加法 ( 1
, 2
, 3
)而不是字符串连接。$number
b
Simply remove let
and the desired behavior 1
, 11
, 111
will occur.
只需删除,就会发生let
所需的行为1
, 。11
111
The other method to perform string concatenation:
执行字符串连接的另一种方法:
b="$b$number"
Yes, simply "let b
become the result of concatenating b
and number
.
是的,只需“让b
成为连接b
和的结果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))
.
作为旁注,b=""
相当于b=
as""
被扩展为一个空字符串。变量的模块运算可以通过算术展开来完成:number=$((RANDOM%9))
.