bash - 为什么即使两个 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
解决方案
大概 $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 ]]
推荐阅读
- python - 将数据框中的多个数字列转换为货币值。使用 Pandas 将 , 和 $ 放在每个值上 ~ Jupyter Notebook
- php - 如何在第 173 行修复 Handlers/FieldsetRepeater.php
- material-ui - 在同一个项目中使用 Material Ui 和 tailwind 是一个好习惯吗
- npm - 如何使用 pug 为全栈网站设置工作流程
- javascript - 当我们在 Promise 解决之前调用 .then 会发生什么?
- py-datatable - 在 google colab 机器上安装新的数据表版本 1.0.0 时出错
- stata - 以长格式查找与记录子集的最大值关联的字符串值
- powerbi - 使用 DAX 来自不同列的累积值
- json - F#: How to deserialize a private discriminated union with Newtonsoft.Json?
- sql - 如何使用分区通过开始和结束日期创建日期范围?