Ubuntu – variable expansion in single quote

bashcommand line

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?

Best Answer

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
Related Question