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.hThe 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.hAlternatively:
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"
EOFor 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