How can I write some lines to a file in a bash script?
I want to write the following into a file ~/.inputrc
"\e[A": history-search-backward
"\e[B": history-search-forward
"\e[C": forward-char
"\e[D": backward-char
Currently I have this working but somewhat ugly method, and I'm sure there should be a better way.
#!/bin/sh
echo \"\\e[A\": history-search-backward > ~/.inputrc
echo \"\\e[B\": history-search-forward >> ~/.inputrc
echo \"\\e[C\": forward-char >> ~/.inputrc
echo \"\\e[D\": backward-char >> ~/.inputrc
Use a here document:
This lets you put the data inline in your shell script. The string
EOF
can be whatever you want, so just pick any string that doesn't appear in your input on a single line by itself.Using the
echo
command for things other than simple strings can be complex and non-portable. There's the GNU version ofecho
(part of coreutils), the BSD version that you'll probably find on MacOS, and most shells haveecho
as a built-in command. All these different versions can have subtly different ways of handling options command-line options (-n
to inhibit the trailing newline,-c
/-C
to enable or disable backslash escapes) and escapes (\e
might or might not be an encoding for the escape character).printf
to the rescue.printf
is probably available as/usr/bin/printf
and/or/bin/printf
, and it's also a built-in in some shells (bash and zsh anyway), but its behavior is much more consistent.Here's the GNU coretuils printf documentation.
For your example, you could write:
That's pretty much it.
Here's one way to reduce the redundancy:
A slightly simpler method would be:
I'm curious why you need to do this though. If you want to setup a file with some specific text, then maybe you should create the skeleton file, and dump it into
/etc/skel
. Then, you cancp /etc/skel/.inputrc ~/.inputrc
in your script.