Shell script — weird behaviour after concatenating string with variables

女生的网名这么多〃 提交于 2019-12-20 05:55:59

问题


I am reading a .properties file from my shell script. I wanted to read some value for some key and after that want to append it in between some string but the output is weird.

#!/bin/bash
# Script used to read Property File
FILE_NAME="Test.properties"
prop_value=$(cat ${FILE_NAME} | grep Address)
echo "ABC${prop_value}DEF"

my Test.properties is like this

Name=Pravin
Age=25
Address=Mumbai
asd=asd

After executing this script I am expecting

ABCAddress=MumbaiDEF 

but I am getting output like

DEFAddress=Mumbai 

What would be the problem here?

If I define any variable in a script it works, but when I read it from file using command expansion it doesn't work.


回答1:


To trim carriage returns from a variable on expansion, you can use ${varname%$'\r'}. Thus:

echo "ABC${prop_value%$'\r'}DEF"

Better would be to save your properties file as a native Unix text file, which contains no carriage returns at all.



来源:https://stackoverflow.com/questions/42511846/shell-script-weird-behaviour-after-concatenating-string-with-variables

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