Linux 在从文件读取的输入中执行命令替换

Linux 在从文件读取的输入中执行命令替换,linux,bash,shell,Linux,Bash,Shell,在shell脚本中如何使脚本读取输入文件字符串中的命令 示例1(script1.sh): 示例2(script2.sh): cat脚本2.sh a=`head -1 input.txt` echo $a 示例input.txt 如果我运行script1.sh,read命令工作正常,但是当我运行script2.sh时,read命令不会执行,而是作为输出的一部分打印出来 因此,我希望script2.sh的输出与script1.sh相同。您的input.txt内容在这里作为脚本有效地执行仅当您完

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

示例1(script1.sh): 示例2(script2.sh): cat脚本2.sh

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

示例
input.txt

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


因此,我希望script2.sh的输出与script1.sh相同。

您的
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"
#/usr/bin/env bash

#^^^^-非/bin/sh;script1.sh中的$''和$(需要计算第一行,因此执行并替换字符串中的
reada

在脚本2.sh中,计算第一行,因此执行
head
得到的字符串被放入变量a中


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

我看不出这里的
$script
有什么意义。在我看来,这是一个漫长的过程:
script=“cat input.txt”
a=$(source@PesaThe,这根本不是
script=“cat input.txt”
。尝试执行它并在实践中检查值,请记住,带有无引号符号的heredocs执行shell解析的部分,这些部分在扩展模板时通常是可取的(命令替换、变量),但忽略了令人惊讶的部分(全局表达式、字符串拆分等).@PesaThe,…关于这一点,请参阅Yep中给出的符合
sh
-的等价物,我现在看到了。感谢您的解释。@charlesduff的答案解决了您的问题,但我认为您的意思是在代码中使用它:
a=“google.analytics.account.id=$(IFS=read-r id;echo“$id”)
。这一点很好。在子shell中运行
读取a
永远不会更改父shell中变量
a
的值。在script2.sh中使用eval$a工作非常感谢大家
google.analytics.account.id=`read a`
#!/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"