bash 如何在shell脚本中将值附加到变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35935919/
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
how to append a value to a variable in shell script
提问by sampath
I am getting a variable value from properties and I am able to access in sh file. but I am unable to append another value to that variable.
我从属性中获取变量值,并且可以在 sh 文件中访问。但我无法向该变量附加另一个值。
Kindly suggest.
请建议。
$ echo "Build ID from properties:"$BUILD_ID
Build ID from properties: abcd_v6_c1
$ echo " num----------------" build_${BUILD_ID}.zip
.zip---------------- build_abcd_v6_c1
Kindly suggest how to append .zipvalue.
请建议如何附加.zip值。
回答by SLePort
It seems you have a Windows carriage returnin your $BUILD_ID
variable.
您的变量中似乎有一个 Windows回车符$BUILD_ID
。
To check, try this command (the carriage return will be visible as a ^M
) :
要检查,请尝试此命令(回车将显示为^M
):
cat -A <<< "$BUILD_ID"
In your terminal,you can try this (to get the ^M
char, use CTRL+ V+ M) :
在你的终端,你可以试试这个(获得^M
字符,使用CTRL+ V+ M):
$ BUILD_ID="585548979^M"
$ echo ${BUILD_ID}text
The result should be :
结果应该是:
text48979
You can clean your variable with a Bash parameter substitution :
您可以使用 Bash 参数替换来清理变量:
$ ID=${BUILD_ID%$'\r'}
$ echo ${ID}text
585548979text
回答by Alex Weitz
Let's say we have a variablevar1=value
.
If I want to add some text to the beginning of the variable I can do:
假设我们有一个变量var1=value
。如果我想在变量的开头添加一些文本,我可以这样做:
var1="some text${var1}"
If I want to add some text to the end, it will be:
如果我想在最后添加一些文本,它将是:
var1="${var1}some text"
回答by Priya
This following way works for me. My .sh file has the following contents:
以下这种方式对我有用。我的 .sh 文件有以下内容:
#!/bin/bash -x
. /usr/test/build.properties
echo $BUILD_ID
echo "num----------------" build_${BUILD_ID}.zip
回答by Devavrata
You can simply use assignment(=)
operator to append text.
您可以简单地使用assignment(=)
运算符来附加文本。
a=don
b=$a" jon"
echo $b #==>don jon
回答by sampath
Thanks all,
谢谢大家,
Able to fix the issue.. it's because of ^M thanks @Kenavoz now I am getting proper ID and able to proceed with the o/p.
能够解决问题..这是因为 ^M 谢谢@Kenavoz 现在我获得了正确的 ID 并能够继续进行 o/p。
Change:BUILD_ID=${ID%$'\r'}
更改:BUILD_ID=${ID%$'\r'}
Thanks, Sampath A
谢谢,萨姆帕特 A