Write some lines to a file with a bash script

陌路散爱 提交于 2019-12-06 08:33:10

问题


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

回答1:


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.




回答2:


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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/7823079/write-some-lines-to-a-file-with-a-bash-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!