2013-01-09 140 views
2

我試圖設置爲我的筆記本電腦硬件靜音按鈕,運行Linux的chrunchbang, 我已經得到了關鍵事件處理工作,並指着一個這樣的腳本:shell腳本的if語句麻煩

curvol=$(amixer get Master | grep 'off') 
if ["$curvol" != ""] 
then 
amixer set Master unmute 
else 
amixer set Master mute 
fi 

按下分配的按鈕會發生什麼,如果靜音,它將取消靜音;但如果它尚未靜音,它將不會靜音。

我認爲問題出現在if語句中,我檢查命令的輸出;無論if是否返回true,它似乎總是在進行取消靜音。

任何幫助將不勝感激!提前致謝。

+0

您是否檢查過'$ curvol'的值是否是您期望的值? –

+1

'''命令/操作符和''''標記周圍包含空格 – 2013-01-09 01:21:20

+0

我添加了一個回顯,它好像不使用grep,並且只是返回amixer的完整輸出獲得主節點 – fredricton1

回答

3

[是命令的名稱(或shell內建,有時)。你需要加上一個空格,它的工作:

if [ "$curvol" != "" ] 
+0

這是工作,現在我感到很傻!謝謝! – fredricton1

+0

不要覺得愚蠢 - 這是''''曾經是'test'命令的同義詞這個事實帶來的常見問題。 –

2

您可以使用grep的返回值:

amixer get Master | grep 'off' &> /dev/null 
if [ $? -eq 0 ] 
then 
    amixer set Master unmute 
else 
    amixer set Master mute 
fi 
+3

更簡單:使用'如果amixer獲得Master | grep -q'off';然後' –

2

看起來這將是一個簡單得多隻寫:

amixer set Master ${curvol:+un}mute 

這相當於:

if test -n "$curvol"; then 
    amixer set Master unmute 
else 
    amixer set Master mute 
fi 

但少得多羅嗦。另請注意,通過使用test而不是[,語法錯誤變得更加困難。

0

你可以用Python做到這一點。我添加了BASH功能來切換靜音狀態。 堅持它〜/ .bashrc

我目前正在使用一臺筆記本電腦,所以,我沒有多個聲卡。
我沒有做任何錯誤檢查。

有關更多示例代碼,請參閱/usr/share/doc/python-alsaaudio/examples/mixertest.py 。

# toggle Master mute            
function tm(){ 
python -c "              
import alsaaudio             

mixerObj = alsaaudio.Mixer()          
currentMute = mixerObj.getmute()[0]        
newMute = not currentMute          
mixerObj.setmute(newMute)          
" 
}