how to append a value to a variable in shell script

独自空忆成欢 提交于 2020-01-16 04:45:09

问题


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.

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 .zip value.


回答1:


It seems you have a Windows carriage return in your $BUILD_ID variable.

To check, try this command (the carriage return will be visible as a ^M) :

cat -A <<< "$BUILD_ID"

In your terminal,you can try this (to get the ^M char, use 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 :

$ ID=${BUILD_ID%$'\r'}
$ echo ${ID}text
585548979text



回答2:


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="some text${var1}"

If I want to add some text to the end, it will be:

var1="${var1}some text"



回答3:


This following way works for me. My .sh file has the following contents:

#!/bin/bash -x
. /usr/test/build.properties
echo $BUILD_ID
echo "num----------------" build_${BUILD_ID}.zip



回答4:


You can simply use assignment(=) operator to append text.

a=don
b=$a" jon"
echo $b #==>don jon



回答5:


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.

Change:BUILD_ID=${ID%$'\r'}

Thanks, Sampath A



来源:https://stackoverflow.com/questions/35935919/how-to-append-a-value-to-a-variable-in-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!