fredricton1
fredricton1

Reputation: 23

shell script if statement trouble

I'm trying to set up a hardware mute button for my notebook running chrunchbang linux, I've got the key event handling working and pointing to a script like this :

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

what happens is on pressing the button assigned, it will unmute if muted; but it won't mute if it isn't already muted.

I think the problem is in the if statement where I check for output from the command; it seems to be always doing the unmute, regardless of whether the if returns true or not.

Any help would be greatly appreciated! Thanks in advance.

Upvotes: 2

Views: 549

Answers (4)

AAAfarmclub
AAAfarmclub

Reputation: 2390

You can do it in Python. I added a BASH function to toggle the mute state. Stick it in ~/.bashrc

I'm currently using a laptop, so, I don't have multiple sound cards.
I'm not doing any error checking.

See /usr/share/doc/python-alsaaudio/examples/mixertest.py for more sample code.

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

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

Upvotes: 0

William Pursell
William Pursell

Reputation: 212654

Seems like it would be a lot simpler to just write:

amixer set Master ${curvol:+un}mute

which is equivalent to:

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

but much less wordy. Also, note that by using test instead of [, the syntax error becomes much more difficult to make.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 225232

[ is the name of a command (or shell builtin, sometimes). You need a space after it for it to work:

if [ "$curvol" != "" ]

Upvotes: 3

perreal
perreal

Reputation: 98118

You can use the return value of grep:

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

Upvotes: 2

Related Questions