【问题标题】:Execute command substitutions in input read from a file在从文件读取的输入中执行命令替换
【发布时间】:2017-12-20 02:39:12
【问题描述】:

在shell脚本中如何让脚本读取输入文件字符串中的命令

示例 1 (script1.sh):

a="google.analytics.account.id=`read a`"
echo $a

示例 2 (script2.sh):

cat script2.sh

a=`head -1 input.txt`
echo $a

样本input.txt

google.analytics.account.id=`read a`

如果我运行script1.shread 命令工作正常,但是当我运行script2.sh 时,read 命令不会执行,而是作为输出的一部分打印出来。

所以我希望 script2.sh 具有与 script1.sh 相同的输出。

【问题讨论】:

  • @CharlesDuffy 的回答解决了您的问题,但我认为您打算在代码中使用它:a="google.analytics.account.id=$(IFS= read -r id; echo "$id")"
  • 好点。在子 shell 中运行 read a 永远不会改变父 shell 中变量 a 的值。

标签: linux bash shell


【解决方案1】:

您的input.txt 内容在此处作为脚本有效执行; 只有在您完全相信这些内容可以在您的机器上运行任意命令时才这样做。也就是说:

#!/usr/bin/env bash
#              ^^^^- not /bin/sh; needed for $'' and $(<...) syntax.

# generate a random sigil that's unlikely to exist inside your script.txt
# maybe even sigil="EOF-$(uuidgen)" if you're guaranteed to have it.
sigil="EOF-025CAF93-9479-4EDE-97D9-483A3D5472F3"

# generate a shell script which includes your input file as a heredoc
script="cat <<$sigil"$'\n'"$(<input.txt)"$'\n'"$sigil"

# run that script
eval "$script"

【讨论】:

  • 我在这里看不到$script 的意义。对我来说似乎还有很长的路要走:script="cat input.txt"。 OP 不只是试图执行input.txt 的第一行并将其放入变量$a 中吗? a=$(source &lt;(head -n 1 input.txt)) 可能会成功。 `
  • @PesaThe,这根本不是script="cat input.txt"。尝试执行它并在实践中检查值,请记住,带有未引用符号的 heredocs 会执行扩展模板时通常需要的 shell 解析部分(命令替换、变量),但会忽略令人惊讶的事情(glob 表达式、字符串-拆分等)。
  • @PesaThe, ...就此而言,请参阅mywiki.wooledge.org/TemplateFiles 中给出的符合sh 的等效项
  • 是的,我现在看到了。谢谢你的解释。
【解决方案2】:

在 script1.sh 中评估第一行,因此 read a 被执行并替换为字符串。

在脚本 2.sh 中,计算第一行,因此将执行 head 的结果字符串放入变量 a。

没有对结果字符串进行重新评估。如果您使用eval $a 添加评估并且input.txt 中的第一行与script1.sh 的第一行完全相同(实际上缺少a="..."),那么您可能会得到相同的结果。正如 CharlesDuffy 建议的那样,heredoc 似乎更准确。

【讨论】:

  • 在 script2.sh 中使用 eval $a 非常感谢大家
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 2012-05-29
  • 2012-10-06
相关资源
最近更新 更多