如何获取存储在文件中的字符串中的变量值?

时间:2017-12-27 21:33:05

标签: bash shell scripting

我有一个包含变量的字符串的文件。我想检索字符串,其中包含在字符串中表示的变量的值。我试过${!var}但没有成功。

一个名为test.line的文件,其中包含字符串和变量:

$ cat test.line 
Hello $var3

一个名为test.sh的bash脚本:

$ cat test.sh 
#!/bin/bash

var1="hello"
var2="goodbye"
var3="again"

## works
str="$var1 and $var2"
echo $str

## does not work--prints $var3 instead of "again"
str="$(cat test.line)"
echo $str

运行时输出test.sh:

$ ./test.sh 
hello and goodbye
Hello $var3

运行时所需的test.sh输出:

$ ./test.sh 
hello and goodbye
Hello again

1 个答案:

答案 0 :(得分:0)

$ cat test.sh
#!/bin/bash

var1="hello"
var2="goodbye"
var3="again"

## works
str="$var1 and $var2"
echo $str

## SOLVED -- Does work
str="$(cat test.line)"
eval echo $str   # This is the line that SOLVED it

运行时test.sh的输出:

$ ./test.sh 
hello and goodbye
Hello again ##This is what I want (SOLVED)