How to append multiple lines to a file with bash, with "–" in front of string

Question very similar to How to append multiple lines to a file with bash but I want to start the file with --, and also append to the file, if possible.

printf "--no-colorn--format-docn--no-profilen" >> ~/.rspec-test

The issue is starting the file with “–” gives me a:

-bash: printf: --: invalid option
printf: usage: printf [-v var] format [arguments]

Is there a way to escape the --? Are there any alternatives? I’m not sure how to do multiple lines using echo, and cat isn’t a good option, I’d like to have it in an automated script.

Asked By: mswieboda

||

Most commands that accept --foo as an option also accept -- by itself as an “end of options, start of arguments” marker – so you could do:

printf -- "--no-colorn--format-docn--no-profilen" >> ~/.rspec-test

But the more specific answer to your exact example is that the first argument to printf is a format specifier, and you’re making things more difficult than necessary by not using printf for its formatting abilities. This would be a better way to do what you want:

printf "%sn" --no-color --format-doc --no-profile >> ~/.rspec-test

That tells printf to take each argument it gets and print it, followed by a newline. Easier than repeating the n yourself, and it avoids the leading -- problem you were facing. And it removes the need to escape any % signs that your strings might contain.

As for how to do multiple lines with echo, you could use:

echo -ne "--no-colorn--format-docn--no-profilen" >> ~/.rspec-test

Or, much more portably:

{ echo --no-color; echo --format-doc; echo --no-profile; } >> ~/.rspec-test

Or using cat along with a here-doc:

cat >>.rspec-test <<EOF
--no-color
--format-doc
--no-profile
EOF
Answered By: godlygeek
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.