Output ${projSRC} to file in Bash script

时间:2016-07-11 19:49:01

标签: bash shell file

I am writing a Bash script that creates a CMakeLists.txt file for a project.
The problem arises at this portion:

    echo "file(GLOB projSRC src/*.cpp)" >> CMakeLists.txt

After that, I need the program to output ${SOURCES} into CMakeLists.txt
I don't mean a variable in the script named SOURCES, I mean it should actually write the plaintext ${SOURCES}.

What I mean is, the final file should look this like:

arbitrary_command(target PROJECT sources ${SOURCES})  

and not like:

arbitrary_command(target PROJECT sources [insert however bash messes it up here])

How can I do this in my Bash script?

2 个答案:

答案 0 :(得分:2)

Use single quotes, not double quotes, for a literal string:

echo 'file(GLOB ${projSRC} src/*.cpp)' >> CMakeLists.txt

That said, you might consider using a heredoc (or even a quoted heredoc) in this case, to write the entire file as one command:

cat >CMakeLists.txt <<'EOF'
everything here will be emitted to the file exactly as written
${projSRC}, etc
even over multiple lines
EOF

...or, if you want some substitutions, an unquoted heredoc (that is, one where the sigil -- EOF in these examples -- isn't quoted at the start):

foo="this"
cat >CMakeLists.txt <<EOF
here, parameter expansions will be honored, like ${foo}
but can still be quoted: \${foo}
EOF

You can also have multiple commands writing output to a single redirection, to avoid paying the cost of opening your output file more than once:

foo=this
{
  echo "Here's a line, which is expanded due to double quotes: ${foo}"
  echo 'Here is another line, with no expansion due to single quotes: ${foo}'
} >CMakeLists.txt

答案 1 :(得分:1)

May be I don't understand your question...

But

echo \${SOURCES}

will print

${SOURCES} 

for you.