Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...