Bash:带有"read"命令和 def 包装在 <<-EOF 中的 shell 脚本



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

概述

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

这个脚本很棒,除了,我不清楚如何通过传递变量$URL来使用此脚本。看来我只能使用静态 URL 字符串传递此脚本,该字符串必须用双引号括起来,然后再次用单引号括起来,例如'"..."'.

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

从 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 ...

谢谢

任何建议都非常感谢!

您需要在$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

相关内容

最新更新