Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

bash - How do I pass an encapsulated variable into a new environment

I have simplified this scenario as much as I can. I am trying to get the second version to work with proper escaped quotes. The first works as expected. Unfortunately I cannot change how the second is going to be called. I am however able to change the value of REALTEST. No matter what I tried with quoting, I can't get the second to accept the spaced string.

This is what I am trying to do:

#!/bin/bash -x
env -i TESTVAR="some spaced string" /bin/bash -l -c "echo $TESTVAR"

REALTEST=TESTVAR="some spaced string"
env -i $REALTEST /bin/bash -l -c "echo $TESTVAR"

Here is my output:

-bash-4.2$ ./test.sh
+ env -i 'TESTVAR=some spaced string' /bin/bash -l -c 'echo $TESTVAR'
some spaced string
+ REALTEST='TESTVAR=some spaced string'
+ env -i TESTVAR=some spaced string /bin/bash -l -c 'echo $TESTVAR'
env: spaced: No such file or directory

Any thoughts on what approach I can take to solve this or is this just flat out not possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Double quotes interpolate, while single quotes do not.

What does this mean? run the following three lines one by one and see for yourself:

life='meaning'; echo $life
life='meaning'; echo '$life'
life='meaning'; echo "$life"
  • The first will echo: meaning
  • The second will echo: $life
  • The third will echo: meaning

Some people double quote everything, just to be sure. I'm one of those that do not like to do that. Use single quotes for non interpolate strings and double for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...