繁体   English   中英

Escaping zsh 别名中的反斜杠和双引号

[英]Escaping Backslashes and Double Quotes in zsh Alias

我正在尝试创建一个应该变成以下命令的别名:

aws ssm start-automation-execution --document-name "AWS-StartEC2Instance" --document-version "\$DEFAULT" --parameters '{"AutomationAssumeRole":[""]}' --target-parameter-name InstanceId --targets '[{"Key":"ResourceGroup","Values":["DemoInstances"]}]' --max-errors "1" --max-concurrency "1" --region ap-southeast-1

做起来很简单

alias startdemoinstances="aws ssm start-automation-execution --document-name "AWS-StartEC2Instance" --document-version "\$DEFAULT" --target-parameter-name InstanceId --targets "[{"Key":"ResourceGroup","Values":["DemoInstances"]}]" --max-errors "1" --max-concurrency "1" --region ap-southeast-1"

在 bash 上,但在 zsh 上,命令变成

aws ssm start-automation-execution --document-name AWS-StartEC2Instance --document-version $DEFAULT --target-parameter-name InstanceId --targets '\''[{Key:ResourceGroup,Values:[DemoInstances]}]'\'' --max-errors 1 --max-concurrency 1 --region ap-southeast-1

我无法让"\逃脱。

看起来您将第一个和最后一个双引号视为整个表达式的“环绕”引号,但这不是它在zshbash中的工作方式。 相反,这是一个由一组带引号和不带引号的字符串组成的表达式,这些字符串因为相邻而被连接起来。

一个简短的例子。 这个:

a=X b=Y c=Z
echo '$a'$b'$c'

将打印:

$aY$c

只有$a$c在单引号中,因此不展开。

由于您的示例中的某些字符(例如[{ )实际上没有被引用,因此 shell 会尝试扩展它们。 它在zsh中失败,因为默认行为是在 glob 没有匹配项时退出。

有几种方法可以修复它。


选项 1 - 使 zsh 的行为类似于 bash:

unsetopt nomatch
alias startdemoinstances="aws ssm start-automation-execution --document-name "AWS-StartEC2Instance" --document-version "\$DEFAULT" --target-parameter-name InstanceId --targets "[{"Key":"ResourceGroup","Values":["DemoInstances"]}]" --max-errors "1" --max-concurrency "1" --region ap-southeast-1"
setopt nomatch

不建议这样做。 有很多方法可以让 go 失控,因为我们指望 shell 以精确的方式忽略特殊字符。


选项 2 - 转义内部双引号,使表达式变成一个长字符串:

alias startdemoinstances="aws ssm start-automation-execution --document-name \"AWS-StartEC2Instance\" --document-version \"\$DEFAULT\" --target-parameter-name InstanceId --targets \"[{\"Key\":\"ResourceGroup\",\"Values\":[\"DemoInstances\"]}]\" --max-errors \"1\" --max-concurrency \"1\" --region ap-southeast-1"

这也应该适用于bash ,这将是一个非常好的主意。


选项 3 - 正如@chepner 建议的那样,使用更具可读性的 function:

function startdemoinstances {
  aws ssm start-automation-execution \
      --document-name 'AWS-StartEC2Instance' \
      --document-version "$DEFAULT" \
      --target-parameter-name 'InstanceId' \
      --targets '[{"Key":"ResourceGroup","Values":["DemoInstances"]}]' \
      --max-errors '1' \
      --max-concurrency '1' \
      --region 'ap-southeast-1'
}

这也应该适用于bash

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM