首页 > 解决方案 > bash字符串变量扩展中的空格字符未读取并在case语句中执行命令

问题描述

我正在使用switchaudio-osx构建 Alfred 工作流程,因此我可以将系统音频输入/输出更改为特定源。编写 shell 脚本很新,我想到了这个:

#!/bin/bash

#Command path
cmd="/usr/local/Cellar/switchaudio-osx/1.0.0/SwitchAudioSource"

#Available sources
source1="Built-in Output"
source2="USB Audio CODEC "
source3="Built-in Microphone"

#Switch output source to
systemOut="$cmd -t output -s $source1"
usbOut="$cmd -t output -s $source2"

#Switch system sound source to
systemSys="$cmd -t system -s $source1"
usbSys="$cmd -t system -s $source2"

#Switch input source to
usbIn="$cmd -t input -s $source2"
systemIn="$cmd -t input -s $source3"

case "{query}" in
    "systemOut") 
        $systemOut 
        $systemSys
    ;;
    "usbOut") 
        $usbOut
        $usbSys
    ;;
    "systemIn") 
        $systemIn
    ;;
    "usbIn") 
        $usbIn
    ;;
    *) 
        echo "No source detected"
    ;;
 esac

运行后,脚本返回错误信息:

Could not find an audio device named "Built-in" of type output.  Nothing was changed.
Could not find an audio device named "Built-in" of type system.  Nothing was changed.

所以不知何故$source1没有完整阅读。通过搜索,我了解了 IFS 设置和使用{}字符串变量,所以我尝试了这些。但是错误消息仍然存在。

当我更改$source1="Built-in Output"为 时"'Built-in Output'",错误消息返回:

Could not find an audio device named "'Built-in" of type output.  Nothing was changed.

当我将 case 语句命令更改$systemOut${systemOut}or"$systemOut"时,两者都返回错误消息:

/usr/local/Cellar/switchaudio-osx/1.0.0/SwitchAudioSource -t output -s 'Built-in Output': No such file or directory
/bin/bash: line 25: /usr/local/Cellar/switchaudio-osx/1.0.0/SwitchAudioSource -t system -s 'Built-in Output': No such file or directory

这个错误信息是什么意思?看起来包含 case 语句中命令的字符串变量没有以正确的方式执行。

我还尝试使用$()``包含具有我的命令的字符串变量,但得到相同类型的错误消息。

在case语句或bash脚本中嵌入shell命令的语法是什么?它不是一个以命令为值的字符串吗?超级新手问题。对不起。

标签: bashvariablessyntaxifsalfred

解决方案


推荐阅读