0

I have a variable userName="testUser" which goes into another string called Data. I am currently not sure how to to get rid of the sing quotes. If I do not give the single quotes the userName will be taken as a string literal.

Data="<Resource  name="\"jdbc/datSource"\" auth="\"Container"\" \n factory="\"org.apache.tomcat.jdbc.pool.DataSourceFactory"\" driverClassName=\"\oracle.jdbc.driver.OracleDriver\"\ username=\"\'${userName}'\"\ />" 

Eventually what I am getting is

name="jdbc/datSource" auth="Container" 
 factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" driverClassName="oracle.jdbc.driver.OracleDriver" username="'testUser'" />

Just need to print username="testUser"

Thanks

Arun
  • 57
  • 5
  • It looks like you are trying to use ES6 template literals (`${...}`) and for these to work, you need to use ES6 back ticks... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals Please let me know if i am missing the point. – Francis Leigh Feb 05 '18 at 16:58
  • *If I do not give the single quotes the userName will be taken as a string literal.* What shell are you using? It works fine for me in `bash` without the single quotes. – lurker Feb 05 '18 at 17:00
  • I am using gitbash – Arun Feb 05 '18 at 17:06

2 Answers2

0

It looks like the problem is you are escaping the $ character. It will work if you remove the single quotes and the \ before the first single quote one.

Data="<Resource name="\"jdbc/datSource"\" auth="\"Container"\" \n factory="\"org.apache.tomcat.jdbc.pool.DataSourceFactory"\" driverClassName=\"\oracle.jdbc.driver.OracleDriver\"\ username=\"${userName}\"\ />"

jephuff
  • 14
  • 1
0

Your quoting would be much less unnecessarily complicated if you used outer single quotes, and only switched to double quotes around the specific string you wish to expand:

userName="Test User"
Data='
<Resource  name="jdbc/datSource" auth="Container"
           factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
           driverClassName="oracle.jdbc.driver.OracleDriver"
           username="'"${userName}"'" />
'

echo "$Data"

...properly emits:

<Resource  name="jdbc/datSource" auth="Container"
           factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
           driverClassName="oracle.jdbc.driver.OracleDriver"
           username="Test User" />

However, you shouldn't ever do this. Use real XML-aware tools (ie. XMLStarlet) to generate or edit XML.

If you were using XMLStarlet, for example, you could run this:

xmlstarlet ed \
  -u '//Resource[@name='jdbc/datSource']/@username' \
  -v "$userName" \
  <in.xml >out.xml

...to change the username for the Resource with name jdbc/datSource in your existing document.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441