shellcript从文件读取variables

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

在第一个脚本文件first.sh中,我是这样做的

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

我使用>来覆盖第一个variables,并为下一个值添加。 所以文件将始终具有最新的值。

有没有比这更好的方法?

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

您可以使用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 

为了读取第二个脚本中的变量,您只需要将其导入(导入):

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

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

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

总是有修改的机会,编写你的变量文件的方法是好的。 你仍然可以改变,如下所示:

echo -e“a = 6 \ nb = 7 \ nc = 8”> test.dat

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

源test.dat

要么

(我的推荐:-))

。 TEST.DAT