Write some lines to a file with a bash script

2019-04-14 06:03发布

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

标签: bash sh
4条回答
聊天终结者
2楼-- · 2019-04-14 06:36

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.

查看更多
forever°为你锁心
3楼-- · 2019-04-14 06:38

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
查看更多
forever°为你锁心
4楼-- · 2019-04-14 06:41

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
查看更多
Viruses.
5楼-- · 2019-04-14 06:43

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.

查看更多
登录 后发表回答