首页 > 解决方案 > 为什么即使两个 elif 语句相似,它们的行为也会不同?

问题描述

出于某种原因,此 elif 语句有效

elif [ $muteStat == 'no' ]; then

而这

elif [ $muteStat == 'no' ]; then

返回此错误

./volumeControl.sh: line 34: [ no: command not found

为什么会这样?

相关代码的图像

更新:在图像中未注释的语句返回错误

代码:

#!/bin/bash

#gets all connected sinks
sinks=$(pactl list short sinks | awk '{print $1}')


#mutes sink
mute() {
 pactl set-sink-mute $1 toggle
}

#adjusts volume of sink 
volume() {
 echo $1 $2
 pactl set-sink-volume $1 $2
}

#loops through all sinks and either mutes or adjusts the volume of them 
for sink in $sinks;
do
 if [[ $# = 1 ]]
 then
  volume $sink $1
 elif [[ $# = 0 ]]
 then
  mute $sink
 fi
done

#gets current volume 
currentVol=$(pactl list sinks | grep "Volume:" | awk '{print $5}' | head -n 1)
#checks if volume is muted, yes/no 
muteStat=$(pactl list sinks | grep -i mute | head -n 1 | awk '{print $2}')

#sends different notification based on whether sound is muted 
if [ $muteStat == 'yes' ]; then
 notify-send -t 1200 "Sound is muted" "Volume is at $currentVol"
#elif [ $muteStat == 'no' ]; then
elif [ $muteStat == 'no' ]; then
 notify-send -t 1200 "Volume is at $currentVol"
fi

标签: bash

解决方案


大概 $muteState 的值为“no”。鉴于错误消息抱怨找不到命令“[ no”(一个单词),因此括号后的空格似乎不是简单的空格。

查看脚本的字符代码:od -c script.sh并寻找“有趣”的字符。实际上,由于它只有第 34 行,请尝试sed -n 34p script.sh | od -c


此外,[命令中的操作数受分词和文件名生成的影响,因此应引用变量

if [ "$muteStat" = yes ] ...
    :
elif [ "$muteStat" = no ] ...

此外,==运算符是 bash 的扩展[,因此如果您使用 bash,不妨使用[[

此外,数值比较使用不同的运算符:[[ $# -eq 1 ]]


推荐阅读