【问题标题】:Bash: Shell script with `read` command and def(s) wrapped within <<-EOFBash:带有`read`命令的Shell脚本和包含在<<-EOF中的def(s)
【发布时间】:2019-10-18 00:09:07
【问题描述】:

我有一个关于如何提供包装在 '"..."' 中的变量的问题,这是 shell 脚本使用 read -d '' var &lt;&lt;- EOF 读取的值的预期格式。

概述

我希望使用这个jq 实用程序库:jq-hopkok。具体来说,bash shell 脚本to-components.sh,它使用jq 将URL 解析为其组件。

这个脚本很棒,除了我不清楚如何通过传递一个变量$URL来使用这个脚本。看来我只能使用静态 URL 字符串传递此脚本,该字符串必须包含在 double-quotes 中,然后再次包含在 single-quotes 中,例如'"..."'

使用静态 URL 值 '"https://..."' 调用 to-components.sh 的示例

来自README.md

#!/usr/bin/env bash
# URL to components
echo '"https://server.example.com/deep/path/file.ext?with-a-parameter=true#and-a-fragment"' | ./to-components.sh

部分结果示例

{
  "value": "https://server.example.com/deep/path/file.ext?with-a-parameter=true#and-a-fragment",
  "valid": true,
  "scheme": {
    "value": "https",
    "valid": true
  },

读取to-components.sh中的URL字符串

shell 脚本to-components.sh 读取此特殊引用的 URL 字符串,必须将其包装 '"..."' 否则将无法解析为组件:

#!/usr/bin/env bash
set -e

# Split up a URL string to an object with the URL components.
read -d '' toComponents <<-'EOF' || true
...
EOF

cat | jq "$toComponents"

期望的目标

我想用带有变量的 URL 字符串调用这个 shell 脚本,例如,我不知道如何构造变量 ???${URL}??? 以便它可以被 shell 脚本解析:

#!/usr/bin/env bash
URL="https://server.example.com/deep/path/file.ext?with-a-parameter=true#and-a-fragment"

# URL to components
echo ???${URL}??? | ./jq-hopkok/src/url/to-components.sh

我尝试了很多方法,但都没有奏效。所有导致错误: parse error: Invalid numeric literal ...

谢谢

非常感谢任何建议!

【问题讨论】:

    标签: bash jq eof


    【解决方案1】:

    您需要在$URL 之前和之后回显文字双引号。一种写清楚的方法是创建一个包含双引号的变量。

    URL="https://server.example.com/deep/path/file.ext?with-a-parameter=true#and-a-fragment"
    dq='"'
    echo "$dq$URL$dq" | ./jq-hopkok/src/url/to-components.sh
    

    【讨论】:

    • 这完美!如果你有时间,你能解释一下为什么吗?我一直在敲击键盘想出一个解决方案。
    • $dq 是双引号。所以这会呼应双引号、URL,然后是另一个双引号。
    • 我明白了。调用echo '"foo"'URL="foo" dq='"' echo "$dq$URL$dq",两者都返回完全相同的结果"foo",这就是它与以read -d '' toComponents &lt;&lt;-'EOF' || true 开头的shell 脚本一起工作的原因。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    相关资源
    最近更新 更多