2015-08-25 30 views
0

我試圖重新啓動與以下bash腳本的GUI(下薄荷+肉桂):找到並執行現有的批處理命令

if ! type gnome-shell > /dev/null; then 
    gnome-shell --replace 
elif ! type cinnamon > /dev/null; then 
    cinnamon --replace 
fi 

我得到一個錯誤信息,該侏儒殼不存在。有沒有辦法編寫這個腳本多平臺?

回答

1

你真正想要的是

type gnome-shell &> /dev/null 

的&>重定向標準輸出和標準錯誤(bash的唯一)。您只是重定向了stdout,因此您仍然收到錯誤消息。 你只對類型的返回值感興趣,而不是輸出。

另外,在那裏做什麼是否定?你叫gnome-shell如果有不是存在嗎?如果你檢查返回值$?記住0是真實的,1是虛假的,彈:(?$)

type gnome-shell 
echo $? # prints '0', indicating success/true, or '1' if gnome-shell does not exist 

返回值,或者更確切地說,退出代碼/退出狀態,就是通過評估如果聲明。

一點點更好:

function cmdExists() 
{ 
    type "$1" &> /dev/null 
} 

function echoErr() 
{ 
    echo "$1" 1>&2 
} 

if cmdExists gnome-shell; then 
    gnome-shell --replace 
elif cmdExists cinnamon; then 
    cinnamon --replace 
else 
    echoErr 'No shell found' 
    exit 
fi 

一些更有益的想法相關主題:

編輯:退出代碼

實際上,除了0以外的每個值在shell中都是false。這是因爲程序使用這些值來指示不同的錯誤。

也有一些例外。裏面(())你可以使用「正常」算術... Shell arithmetic

+0

謝謝,我從來沒有想過這個'記住0是真實的,1是殼'部分錯誤。 :D – inf3rno

+0

不客氣。我在退出代碼上添加了更多的細節。 –