bash - 别名导致错误 : syntax error near unexpected token `('

标签 bash alias

我正在尝试运行以下 bash 并收到错误:bash: syntax error near unexpected token `('.

.bashrc:

alias "ota"='/cygdrive/d/Program Files (x86)/Arduino/hardware/esp8266com/esp8266/tools/espota.py' 

我正在尝试运行以下命令:

ota --help

最佳答案

tl;dr

  • 您需要引用您的别名命令,不仅是为了它的定义也是为了它的使用 原样在生成的命令行上。

  • 在您的情况下,最简单的解决方案是使用 外部 '...'内部 引号的组合。 ." quoting(存在其他解决方案;请注意,使用 "..." 进行内部引用意味着如果您的定义包含变量引用,则它们会在别名已使用):

alias ota='"/cygdrive/d/Program Files (x86)/Arduino/hardware/esp8266com/esp8266/tools/espota.py"'

定义别名时,两个引用(转义)上下文会起作用:

  • 在您定义别名时引用。

  • 在命令上下文中引用使用的别名。


别名定义中的引号允许您定义别名 ota 而不会出现语法错误:

您将别名 ota 定义为以下文字:
/cygdrive/d/Program Files (x86)/Arduino/hardware/esp8266com/esp8266/tools/espota.py
即,由于使用了 '...'(单引号),RHS 上字符串的文字内容。


但是,当您在命令 ota --help使用这个别名时,它的定义变成了命令行的文字,不带引号的部分, Bash 尝试执行以下损坏的命令:

/cygdrive/d/Program Files (x86)/Arduino/hardware/esp8266com/esp8266/tools/espota.py --help

基于通常的shell expansions , 该命令处理如下:

  • /cygdrive/d/Program 被解释为要执行的命令(第一个空格之前的所有内容),因为 word splitting 将未引用的标记拆分为命令行由空格组成单词。

  • 因此,文件(x86)/Arduino/hardware/esp8266com/esp8266/tools/espota.py--help 成为该命令的参数,但是:(),当使用时未加引号,因为它们是这里是 shell 的控制运算符:它们用于创建子 shell,但是作为参数的一部分这样做在语法上是无效,这就是为什么您在意外标记 `(' 附近看到 语法错误
    (在未找到命令 /cygdrive/d/Program 的运行时错误有机会启动之前)。

上面说明了在别名定义的嵌入部分进行适当引用的必要性,如顶部所示。
可以在下面找到替代解决方案。


引用备选方案:

# Using *outer double quotes with inner double quotes* would work here too,
# although if the definition contained variable references / command or 
# arithmetic substitutions, they'd be expanded at *definition* time.
alias ota="'...'"

# Using an *ANSI C-quoted string ($'...')* inside of which you can use
# \' to escape embedded single quotes (but you need to be aware of
# the meaning of other \-based escape sequences).
alias ota=$'\'...\''

# Using *character-individual quoting*, with \ preceding each shell 
# metacharacter (as in @sorontar's answer).
alias ota='/cygdrive/d/Program Files\ \(x86\)...'

改用函数:

@ ruakh指出使用函数而不是别名可以完全绕过两层引用的麻烦:

function ota() { 
 '/cygdrive/d/Program Files (x86)/Arduino/hardware/esp8266com/esp8266/tools/espota.py' "$@"
}

关于bash - 别名导致错误 : syntax error near unexpected token `(' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40697288/

相关文章:

bash - 管道输出不写入标准输出的程序

linux - echo - 语法错误 : Bad substitution

build - 使用 CMake,我如何将 "install an alias"发送到库?

sql - 在 PostgreSQL 查询中使用别名返回 "column does not exist"

c++ - 别名成员对象方法的最佳方法? "Passthrough methods"

apache - MAMP Apache Alias 始终映射到文档根目录

bash - 计算 bash 中的功率

Python 2.6 在 Ubuntu 上导入包 (psyco)

bash - 我如何在 shell 脚本中检查 IP 版本(4 或 6)

linux - 如何使用别名来grep日志文件的尾部?