2014-12-06 30 views
0

我正在gedit上編寫我的代碼,並且我想使用if語句來獲取最新的錯誤和警告消息,如果發生錯誤,那麼我應該收到警告消息。如何在bash中使用if語句來顯示錯誤和警告消息

cp /Volumes/Documents/criticalfile.txt /Volumes/BackUp/. 
if [ "?" != 0 ]; then 
    echo "[Error] copy failed!" 1>&2 
    exit 1 
fi 

我已經使用了上面的代碼,但我不確定它的正確與否。

+0

這是'如果[$? != 0] ...'。但是,你真的可以做'如果! cp /Vols/Docs/File.txt/Vols/Bkup;然後回顯錯誤...; fi'。學習使用'set -vx'(或至少'set -x')來查看代碼執行時的調試/追蹤。 '$?'是最後執行的命令的返回狀態。 「0」表示錯誤,而不是「0」表示錯誤。祝你好運。附:非常好的「selfie」; - > – shellter 2014-12-06 01:29:01

+1

您也可以使用**複合語句**進行錯誤檢查:'cp /Volumes/Documents/criticalfile.txt/Volumes/BackUp/|| {回聲「[錯誤]複製失敗!」 1>&2 && exit 1; }'不能代替'if ... else ... fi',但對於簡短的命令,它會做簡短的代碼。 – 2014-12-06 01:37:08

回答

1

你必須使用的

if [ "$?" != 0 ]; then 

代替

if [ "?" != 0 ]; then 

讓說我要複製一個文件,但我不知道我是否會得到一個錯誤。我用下面的命令

cp -f /root/Desktop/my_new_file */root/t 

肯定這會給我一個錯誤,因爲複製到「* /根/ T」是不可能的。

我可以用下面的代碼

#!/bin/bash 
cp -f /root/Desktop/my_new_file */root/t 
if [ "$?" = 0 ];then 
echo "No error" 
else 
echo "We have error!" 
fi 

我的輸出(請注意,條件是工作)

cp: cannot create regular file `*/root/t': No such file or directory 
We have error 

檢查這個現在讓我們說,我想將文件複製到一個可能的位置像

cp -f /root/Desktop/my_new_file /root/t 

我會從cp命令沒有錯誤

輸出

No error 
0

沒有,if [ "?" != 0 ]是不正確的。 您正在尋找if [ $? != 0 ]

但更好的方法:

if ! cp /Volumes/Documents/criticalfile.txt /Volumes/BackUp/ 
then 
    echo "[Error] copy failed!" >&2 
    exit 1 
fi 

我也是從1>&2下降了1,爲>&2是一回事。

0

修復您的代碼。

cp /Volumes/Documents/criticalfile.txt /Volumes/BackUp/ > /dev/null 2>&1 
if [ "$?" != 0 ]; then 
    echo "[Error] copy failed!" 
    exit 1 
fi 

一個襯墊

cp infile /Volumes/BackUp/ > /dev/null 2>&1 || echo "[Error] copy failed!"