簡體   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