wim
wim

Reputation: 362627

Write some lines to a file with a bash script

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

Upvotes: 5

Views: 28103

Answers (4)

mmrtnt
mmrtnt

Reputation: 392

That's pretty much it.

Here's one way to reduce the redundancy:

TEXT="\"\\e[A\": history-search-backward 
\"\\e[B\": history-search-forward 
\"\\e[C\": forward-char 
\"\\e[D\": backward-char"

echo "$TEXT" > ~/.inputrc

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263237

Using the echo command for things other than simple strings can be complex and non-portable. There's the GNU version of echo (part of coreutils), the BSD version that you'll probably find on MacOS, and most shells have echo 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:

(
   printf '"\e[A": history-search-backward\n'
   printf '"\e[B": history-search-forward\n'
   printf '"\e[C": forward-char\n'
   printf '"\e[D": backward-char\n'
) > ~/.inputrc

Upvotes: 2

Adam Rosenfield
Adam Rosenfield

Reputation: 400224

Use a here document:

#!/bin/bash
cat >~/.inputrc <<EOF
"\e[A": history-search-backward
"\e[B": history-search-forward
"\e[C": forward-char
"\e[D": backward-char
EOF

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.

Upvotes: 4

Spencer Rathbun
Spencer Rathbun

Reputation: 14900

A slightly simpler method would be:

cat > ~/.inputrc << "EOF"
"\e[A": history-search-backward
"\e[B": history-search-forward
"\e[C": forward-char
"\e[D": backward-char
EOF

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 can cp /etc/skel/.inputrc ~/.inputrc in your script.

Upvotes: 15

Related Questions