Linux Cat


原文链接: Linux Cat

Here Documents

sudo tee newfile <<EOF
line 1
line 2
line 3
EOF

root权限写入

sudo bash -c 'cat >  /var/www/.gitconfig <<EOF
[user]
  name = rinetd
  email = rinetd@163.com
[core]
  symlinks = false
  autocrlf = false
  whitespace = trailing-space,space-before-tab,indent-with-non-tab,cr-at-eol
[gui]
  encoding = utf-8          # 图形界面编码
[i18n]
  commitencoding = utf-8    # 提交信息编码
  logoutputencoding = utf-8 # 输出 log 编码
[alias]
  st = status -sb
  l = log --pretty=oneline -n 20 --graph --abbrev-commit
EOF'

Read the Advanced Bash-Scripting Guide Chapter 19. Here Documents.

Here's an example which will write the contents to a file at /tmp/yourfilehere

cat << EOF > /tmp/yourfilehere
These contents will be written to the file.

    This line is indented.

EOF

Note that the final 'EOF' (The LimitString) should not have any whitespace in front of the word, because it means that the LimitString will not be recognized.

In a shell script, you may want to use indentation to make the code readable, however this can have the undesirable effect of indenting the text within your here document. In this case, use <<- (followed by a dash) to disable leading tabs (Note that to test this you will need to replace the leading whitespace with a tab character, since I cannot print actual tab characters here.)

#!/usr/bin/env bash

if true ; then

cat <<- EOF > /tmp/yourfilehere
The leading tab is ignored.
EOF

fi

If you don't want to interpret variables in the text, then use single quotes:

cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF

To pipe the heredoc through a command pipeline:

cat <<'EOF' | sed 's/a/b/'
foo
bar
baz
EOF

Output:

foo
bbr
bbz

... or to write the the heredoc to a file using sudo:

cat <<'EOF' | sed 's/a/b/' | sudo tee /etc/config_file.conf
foo
bar
baz
EOF

`