简体   繁体   English

Bash:用字符串格式化环境变量

[英]Bash: Format environment variables in string

How does one format a string leveraging an environment variable within at the command line? 在命令行中如何利用环境变量格式化字符串? For example, I want to curl and pass some variable, ie: 例如,我想卷曲并传递一些变量,即:

curl -X POST --data-urlencode 'payload={"text": "I want to print an environment variable here, eg a path: $PATH"}' https://someapi.com/

The easy answer is to change the kind of quotes you're using: 简单的答案是更改您使用的报价类型:

curl -X POST --data-urlencode \
  'payload={"text": "I want to print an environment variable here, eg a path: '"$PATH"'"}' \
   https://someapi.com/

Notably, this is still using single-quotes on the outside (so you don't need to change your payload), but then it ends the single quotes, starts double quotes, and embeds your substitution in those double quotes (before ending them and switching back to single quotes, within which literal -- rather than syntactic -- double quotes can be embedded). 值得注意的是,它仍然在外部使用单引号(因此您不需要更改有效负载),但是随后它结束了单引号, 开始了双引号,并将替换内容嵌入到这些双引号中(在结束它们之前,切换回单引号,可以在其中嵌入文字(而不是句法)。

A variant on this approach, which avoids the need for syntactic quotes mixed into the document content, is to used an unquoted heredoc, as advised by @chepner in the comments : @chepner在评论中建议,此方法的一种变体是避免将句法引号混入文档内容中,而是使用未引号的heredoc:

curl -X POST --data-urlencode @- https://someapi.com/ <<EOF
payload={"text": "I want to print an environment variable here, eg a path: $PATH"}
EOF

The better answer is to use a tool that knows how to format JSON; 更好的答案是使用知道如何格式化JSON的工具。 jq is a widely popular choice. jq是广受欢迎的选择。 Consider the following example: 考虑以下示例:

text="I want to print an environment variable here, eg a path: \"$PATH\""
curl -X POST --data-urlencode @- https://someapi.com/ <<EOF
payload=$(printf '%s\n' "$text" | jq -R '{text: .}')
EOF

This way you're guaranteed valid output, even if your environment variable contains backslashes, literal quotes, nonprintable characters, or whatever else may come. 这样,即使您的环境变量包含反斜杠,文字引号,不可打印的字符或其他可能出现的内容,也可以保证输出有效。

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

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