【问题标题】:How to interpolate a string that was sent as an argument?如何插入作为参数发送的字符串?
【发布时间】:2018-08-26 01:19:22
【问题描述】:

我对文件系统的访问权限有限,我想像这样设置通用通知处理程序调用:

notificator.sh "apples" "oranges" "There were $(1) and $(2) in the basket"

notificator.sh 内容:

#!/bin/sh
echo $3

得到如下输出:

"There were apples and oranges in the basket"

有可能吗?怎么做?如果它是内置的 sh 解决方案,我会更喜欢。 我实际上是在尝试通过 curl post 参数将结果字符串 ($3) 作为消息发送给电报机器人,但试图简化这种情况。

【问题讨论】:

  • $(...),还是${...}?你真的需要它是$1,而不是$fruit1 之类的吗?
  • 此外,值得评估您是否以及在多大程度上信任您的数据 - 一些简单的答案会带来安全风险(在遵循任何涉及 eval 的建议之前,请参阅 BashFAQ #48)。

标签: shell command-line-arguments string-interpolation


【解决方案1】:

通过对您的$3 进行一些更改,我们可以轻松完成这项工作。

首先,让我们定义$1$2$3

$ set -- "apples" "oranges" 'There were ${one} and ${two} in the basket'

现在,让我们强制替换为$3

$ one=$1 two=$2 envsubst <<<"$3"
There were apples and oranges in the basket

注意事项:

  1. $(1) 尝试运行名为 1 的命令,甚至在脚本运行之前可能会生成错误。请改用${var}

  2. 为了让这个方法起作用,我们需要重命名$3 中的变量。

  3. envsubst 是 GNU gettext-base 软件包的一部分,应该在 Linux 发行版中默认可用。

Charles Duffy 致敬。

脚本形式

考虑这个脚本:

$ cat script.sh
#!/bin/sh
echo "$3" | one=$1 two=$2 envsubst

我们可以执行上面的:

$ sh script.sh "apples" "oranges" 'There were ${one} and ${two} in the basket'
There were apples and oranges in the basket

作为替代方案(再次向Charles Duffy 致敬),我们可以使用 here-doc:

$ cat script2.sh
#!/bin/sh
one=$1 two=$2 envsubst <<EOF
$3
EOF

运行这个版本:

$ sh script2.sh "apples" "oranges" 'There were ${one} and ${two} in the basket'
There were apples and oranges in the basket

另类

以下脚本不需要envsubst

$ cat script3.sh
#!/bin/sh
echo "$3" | awk '{gsub(/\$\{1\}/, a); gsub(/\$\{2\}/, b)} 1' a=$1 b=$2

使用我们的参数运行这个脚本,我们发现:

$ sh script3.sh "apples" "oranges" 'There were ${1} and ${2} in the basket'
There were apples and oranges in the basket
$ sh script3.sh "apples" "oranges" 'There were ${1} and ${2} in the basket'
There were apples and oranges in the basket

【讨论】:

  • $1$2 不在环境中,那么envsubst 怎么能看到它们呢?我希望您需要将它们复制到命名的导出变量中。
  • ...即。 fruit1=$1 fruit2=$2 envsubst &lt;&lt;&lt;"$3",第三个参数为There were ${fruit1} and ${fruit2} in the basket,等等。
  • 复制当前给出的答案中的代码 (Revision 2),包括 set -- 行,输出为 There were and in the basket
  • @CharlesDuffy 好奇。正如答案所示,它对我有用。我从刚才的答案中复制并粘贴了它,它仍然有效。
  • 。看看set 行中的双引号是如何出现的?因此,如果你运行它两次,第二次它就会自我反馈。
猜你喜欢
  • 2011-06-30
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 2020-10-10
相关资源
最近更新 更多