【问题标题】:How to assign variables from the file in a loop如何在循环中从文件中分配变量
【发布时间】:2018-07-10 19:39:54
【问题描述】:

我正在尝试编写一个 bash 脚本,该脚本将从文件中读取变量对,然后在循环中使用它们。我正在尝试使用这个

while read p; do $p; echo "$a and $b"; done < text.txt

text.txt 包含以下内容:

a="teststring"; b="anothertest"
a="teststring1"; b="anothertest1"
a="teststring2"; b="anothertest2" 

输出如下所示:

bash: a="teststring";: command not found
 and
bash: a="teststring1";: command not found
 and

我发现了类似的问题command line arguments from a file content

但无法弄清楚如何将答案应用于我的特定案例。谢谢!

【问题讨论】:

标签: bash file variables


【解决方案1】:

一个使用邪恶eval的解决方案,仅用于测试目的,不用于生产:

while read line; do
    eval "$line"
    echo "$a and $b"
done < file.txt

输出:

teststring and anothertest
teststring1 and anothertest1
teststring2 and anothertest2

请阅读

http://wiki.bash-hackers.org/commands/builtin/eval

【讨论】:

  • 打败我,包括警告eval!个人使用很好,用于编写脚本,但不能用于生产。
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多