简体   繁体   中英

Add variable value into string

I want to add a variable value to string content quoted with ' ' because of the special characters inside. For example:

a=500
str='#Test
d-i partman-auto/expert_recipe string \
boot-root :: \
   $a 10000 1000000000 ext4 \
   $primary{ } $bootable{ } \
   method{ format } format{ } \
   use_filesystem{ } filesystem{ ext4 } \
   mountpoint{ / } \
.
'

Unfortunately, I can't operate with the value of $a inside the ' '. It's aways returning me $a versus its value=500

You need to leave the "inside" of the single quotes.
Close and re-open the single quotes:

a=500
primary=one
bootable=two
str='#Test
d-i partman-auto/expert_recipe string \
boot-root :: \
   '"$a"' 10000 1000000000 ext4 \
   '"$primary"'{ } '"$bootable"'{ } \
   method{ format } format{ } \
   use_filesystem{ } filesystem{ ext4 } \
   mountpoint{ / } \
.
'
echo "$str"

Your options are:

Interpolate all $ variables (using " ) — and escape any dollar signs that you want to retain:

EXPAND_THIS=100
echo "
$EXPAND_THIS
\$DONT_EXPAND_THIS
"

Or interpolate no $ variables (using ' ) — and start a new, interpolated, string whenever you do want to interpolate a variable:

echo '
'$EXPAND_THIS'
$DONT_EXPAND_THIS
'

Surrounding in quotes the variables that you want interpolated, may provide safety in some situation (though I can't currently think of an example):

echo 'blah
blah
'"$EXPAND_THIS"'
$DONT_EXPAND_THIS
'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM