M BUZZ CRAZE NEWS
// general

variable expansion in single quote

By Mia Morrison

I have have string in single quotes. Inside which I want to insert a variable and expand it. I know in bash variable expansion works with double quotes only. But I'm still not able to make it work.

e.g.:

TOOLS_DIR="/tools"
echo '#define SYS_VIMRC_FILE "${TOOLS_DIR}/etc/vimrc"' >> src/feature.h

The result I get is like this:

#define SYS_VIMRC_FILE "${TOOLS_DIR}/etc/vimrc"

And, the expected output is:

#define SYS_VIMRC_FILE "/tools/etc/vimrc"

How can I solve this issue?

2 Answers

Your double quotes are technically still inside single quotes so no expansion can happen. You can close the single quotes before starting the double quotes and do the reverse at the end of that inner section to achieve what you want:

TOOLS_DIR="/tools"
echo '#define SYS_VIMRC_FILE "'"$TOOLS_DIR"'"/etc/vimrc' >> src/feature.h

Alternatively:

TOOLS_DIR="/tools"
printf '#define SYS_VIMRC_FILE "%s"/etc/vimrc\n' "$TOOLS_DIR" >> src/feature.h
4

Your variable won't expand because you have the string delimited with 'try a heredoc

TOOLS_DIR="/tools"
cat <<- EOF >> src/feature.h #define SYS_VIMRC_FILE "${TOOLS_DIR}/etc/vimrc"
EOF

or you could change to " and escape the inner "'s

TOOLS_DIR="/tools"
echo "#define SYS_VIMRC_FILE \"${TOOLS_DIR}/etc/vimrc\"" >> src/feature.h
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy