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.


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?


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:

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


printf '#define SYS_VIMRC_FILE "%s"/etc/vimrc\n' "$TOOLS_DIR" >> src/feature.h
  • What you are suggesting doesn't help me out as I want "/tools/etc/vimrc". The whole path in " – Abhimanyu Saharan May 13 '16 at 23:23
  • I've upvoted this, because the idea is really cool. the OP wants the resulting string to be wrapped in " so I think you could add these extra " inside your single quotes, like '#define SYS_VIMRC_FILE "'"$TOOLS_DIR"'"/etc/vimrc' – the_velour_fog May 13 '16 at 23:26
  • I missed the double quotes were expected to stay in echo output. Answer fixed. – jlliagre May 13 '16 at 23:31
  • @the_velour_fog Indeed, they can be added. – jlliagre May 13 '16 at 23:33

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

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

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

echo "#define SYS_VIMRC_FILE \"${TOOLS_DIR}/etc/vimrc\"" >> src/feature.h
  • Isn't there any other way? #define ... should be in ' – Abhimanyu Saharan May 13 '16 at 23:24
  • @AbhimanyuSaharan what do you mean #define ... should be in '? – the_velour_fog May 13 '16 at 23:29
  • @AbhimanyuSaharan is #define.. not appearing in the final output string? – the_velour_fog May 13 '16 at 23:30

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.