2013-03-28 231 views
23

在我的shell腳本,我得到了這幾行:抑制shell腳本錯誤消息

rm tempfl.txt 
rm tempfl2.txt 

如果這些都不存在,我得到的錯誤信息:

rm: tempfl2.txt: No such file or directory 
rm: tempfl.txt: No such file or directory 

有沒有辦法只能抑制這些即使它們並不總是顯示消息,因爲這些文件可能存在?

+0

看看這裏:http://stackoverflow.com/questions/12785533/command-not-found-message-is-redirected-too – ConcurrentHashMap 2013-03-28 10:00:32

回答

40

你有兩個選擇:

禁止rm警告

$ rm tempfl.txt 2> /dev/null 

重定向腳本輸出/dev/null

$ ./myscript.sh 2> /dev/null 

後者有丟失了所有其他的警告消息的缺點由您的腳本生成。

+2

rm -f應該小心使用。 – hetepeperfan 2013-03-28 10:01:52

+0

好點,謝謝 – kamituel 2013-03-28 10:02:39

2

你應該重定向的所有錯誤消息到/ dev/null的像

rm tempfl2.txt 2> /dev/null 
2

添加到上述問題的答案:這可能是一個更好的主意,讓錯誤信息(如拒絕許可或一些這樣的)。只是測試文件的存在,刪除它之前:

[ -f file.txt ] && rm file.txt 

這是假設一個Bourne外殼一樣,例如慶典。上面有額外的好處,它不會嘗試刪除一個目錄,rm不能做的事情。

+0

感謝這個工作太 – 2013-03-28 10:19:42

5

試試這個命令:

rm -f tempfl.txt 

-f選項行爲是這樣的:

-f, --force ignore nonexistent files, never prompt 

的命令也不會在病例報告非零錯誤代碼的文件不存在。

+0

你能給出更多的答案解釋嗎? – GraphicsMuncher 2014-02-19 15:09:47

0

我們可以使用2> /dev/null抑制輸出誤差和|| true確保成功退出狀態:

rm foo 
=> rm: cannot remove ‘foo’: No such file or directory 

rm foo 2> /dev/null 
echo $? 
=> 1 

rm foo 2> /dev/null || true 
echo $? 
=> 0 

如果你是在一個shell腳本,生成文件中使用命令,等等,也許你需要這個。