重复输出字符串
本文鏈接: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代碼?? [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腳本頻繁執行時的奇怪現象。
總結
- 上一篇: shell 中数学计算总结
- 下一篇: 关于凸优化的一些简单概念