shellscript从文件中读取变量

时间:2012-07-24 10:15:32

标签: linux shell unix

我是shell脚本新手。我正在开发一个项目,其中需求就像一个脚本文件将设置变量而另一个脚本文件必须获取这些变量并对其进行操作。我将变量从第一个脚本存储到一个文件中,在第二个脚本文件中我正在读取它。

在第一个脚本文件first.sh中,我正在做

echo "a=6" > test.dat
echo "b=7" >> test.dat
echo "c=8" >> test.dat

我使用>作为覆盖的第一个变量以及它附加的下一个值。因此文件将始终具有最新值。

有没有比这更好的方法?

在第二个脚本文件中,如何读取和填充适当的值?

4 个答案:

答案 0 :(得分:8)

您可以使用source

从脚本加载此变量
source test.dat

或只是

. test.dat

示例:

$ echo "a=6" > test.dat ; echo "b=7" >> test.dat ; echo "c=8" >> test.dat
$ cat test.dat 
a=6
b=7
c=8
$ . test.dat
$ echo $a $b $c
6 7 8

如果您有一个生成这些变量的脚本/程序,您也可以使用eval

示例:

$ cat generate.sh
echo a=6
echo b=7
echo c=8

$ bash generate.sh 
a=6
b=7
c=8

$ eval $(bash generate.sh)
$ echo $a $b $c
6 7 8

答案 1 :(得分:1)

要读取第二个脚本中的变量,您只需要获取它(导入它):

## Put this line in your second script
. test.dat

答案 2 :(得分:0)

在编写文件方面,有不同的方法。哪个更好取决于很多因素。一种常见的方法是使用heredoc:

cat > test.dat << EOF
a=6
b=7
c=8
EOF

答案 3 :(得分:0)

总是有机会进行修改,编写变量文件的方法很好。您仍然可以按如下方式更改:

  

echo -e“a = 6 \ nb = 7 \ nc = 8”&gt; TEST.DAT

要通过脚本读取变量文件,可以添加以下内容:

  

source test.dat

(我的建议: - ))

  

。 TEST.DAT

相关问题