Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

20.3. I/O 重定向

		
cat <<End-of-message
   8 -------------------------------------
   9 This is line 1 of the message.
  10 This is line 2 of the message.
  11 This is line 3 of the message.
  12 This is line 4 of the message.
  13 This is the last line of the message.
  14 -------------------------------------
End-of-message
		
		

		
MYSQL=mysql
MYSQLOPTS="-h $zs_host -u $zs_user -p$zs_pass $zs_db"

$MYSQL $MYSQLOPTS <<SQL
SELECT
        category.cat_id AS  cat_id ,
        category.cat_name AS  cat_name ,
        category.cat_desc AS  cat_desc ,
        category.parent_id AS  parent_id ,
        category.sort_order AS  sort_order ,
        category.measure_unit AS  measure_unit ,
        category.style AS  style ,
        category.is_show AS is_show ,
        category.grade AS  grade
FROM  category
SQL
		
		

<<-LimitString可以抑制输出时前边的tab(不是空格). 这可以增加一个脚本的可读性.

		
cat <<-ENDOFMESSAGE
	This is line 1 of the message.
	This is line 2 of the message.
	This is line 3 of the message.
	This is line 4 of the message.
	This is the last line of the message.
ENDOFMESSAGE

		
		

关闭参数替换

		
NAME="John Doe"
RESPONDENT="the author of this fine script"

cat <<'Endofmessage'

Hello, there, $NAME.
Greetings to you, $NAME, from $RESPONDENT.

Endofmessage
		
		
		
NAME="John Doe"
RESPONDENT="the author of this fine script"

cat <<\Endofmessage

Hello, there, $NAME.
Greetings to you, $NAME, from $RESPONDENT.

Endofmessage
		
		

20.3.1. stdout

$ ln -s /dev/stdout test
$ cat file > test
			

20.3.2. error 重定向

			
your_shell 2>&1
			
			

错误输出演示

			
[root@localhost ~]# id ethereum
id: ethereum: no such user

# 这里可以看到错误输出 id: ethereum: no such user

[root@localhost ~]# id ethereum > test
id: ethereum: no such user

我们尝试将他重定向到文件 test,但是结果仍是输出 id: ethereum: no such user 

[root@localhost ~]# cat test 
[root@localhost ~]#

查看 test 文件,内容空。
			
			

继续做实验

			
[root@localhost ~]# id ethereum > test 2>&1 
[root@localhost ~]# cat test 
id: ethereum: no such user
			
			

测试实验结果成功了,将错误输出转到标准输出,然后写入文件。

20.3.3. 使用块记录日志

			
{
	...
	...
} > $LOGFILE 2>&1
			
			

20.3.4. tee - read from standard input and write to standard output and files

echo 1 > /proc/sys/net/ipv4/ip_forward
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward;
			
重定向到文件
				
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://du8c1in9.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker
				
				
nettee - a network "tee" program

				

20.3.5. 创建文件

			
cat << EOF > foo.sh
   printf "%s was here" "$name"
EOF

cat >> foo.sh <<EOF
   printf "%s was here" "$name"
EOF
			
			

20.3.6. 快速清空一个文件的内容

$ > /www/access.log