重复输出字符串

本文链接:http://codingstandards.iteye.com/blog/826940   (转载请注明出处)

用途说明

yes命令用于重复输出字符串(output a string repeatedly until killed)。这个命令可以帮你自动回答命令行提示,例如,进入一个含有多个文件的目录,执行 "yes | rm -i *",所有的 rm: remove regular empty file `xxx'? 提示都会被自动回答 y。这在编写脚本程序的时候会很用处。yes命令还有另外一个用途,可以用来生成大的文本文件。

 

常用参数

yes命令不指定参数时,不断的输出y;指定字符串参数时,就不断的输出该字符串。要终止输出,必须杀掉该进程,比如按Ctrl+C,或killall yes。(Repeatedly output a line with all specified STRING(s), or ‘y’.)比如:要不断输出n时,输入yes n。

 

使用示例

示例一 删除文件时自动回答y

[root@web ~]# ls -l *.txt 
-rw-r--r-- 1 root root     7 11-28 11:54 1.txt
-rw-r--r-- 1 root root 10217 07-06 13:10 data.txt
[root@web ~]# yes | rm -i *.txt 
rm:是否删除 一般文件  "1.txt" | rm -i.txt”? rm:是否删除 一般文件 “data.txt”? [root@web ~]# yes | rm -i *.txt       
rm: lstat “*.txt” 失败: 没有那个文件或目录
[root@web ~]# ls -l *.txt      
ls: *.txt: 没有那个文件或目录
[root@web ~]#

 

示例二 生成大的文本文件

下面的脚本把yes命令输出的内容保存到文件中,然后1秒钟之后停止输出。在这台测试机器上,生成了一个93M的文件。

 

Bash代码   收藏代码
  1. #!/bin/sh  
  2.   
  3. yes hello >hello.txt &  
  4. PID=$!  
  5.   
  6. sleep 1  
  7. kill $PID  
  8.   
  9. ls -l hello.txt  
 

[root@web ~]# cat yes.sh 
#!/bin/sh

yes hello >hello.txt &
PID=$!

sleep 1
kill $PID

ls -l hello.txt

[root@web ~]# ./yes.sh 
-rw-r--r-- 1 root root 93003776 11-28 14:02 hello.txt
./yes.sh: line 9:  5771 已终止                  yes hello > hello.txt
[root@web ~]# ./yes.sh 
-rw-r--r-- 1 root root 95346688 11-28 14:09 hello.txt
./yes.sh: line 9:  7072 已终止                  yes hello > hello.txt
[root@web ~]# ./yes.sh 
-rw-r--r-- 1 root root 0 11-28 14:09 hello.txt
[root@web ~]# ./yes.sh 
-rw-r--r-- 1 root root 0 11-28 14:09 hello.txt
[root@web ~]# ./yes.sh 
-rw-r--r-- 1 root root 0 11-28 14:09 hello.txt
[root@web ~]# ./yes.sh 
-rw-r--r-- 1 root root 94040064 11-28 14:10 hello.txt
[root@web ~]# ./yes.sh 
-rw-r--r-- 1 root root 0 11-28 14:10 hello.txt
[root@web ~]# ./yes.sh 
-rw-r--r-- 1 root root 0 11-28 14:10 hello.txt

[root@web ~]#

问题出现了:如果频繁的执行这个脚本,就会发现竟然生成0字节的文件,为何?

 

问题思考

1. 请分析解释上面的yes.sh脚本频繁执行时的奇怪现象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值