简体   繁体   English

重击:回声提取变量

[英]Bash: echo extract variables

Suppose there's a script called 'test.sh': 假设有一个名为“ test.sh”的脚本:

#!/bin/bash
while read line; do
    APP=/apps echo "$line"
done < ./lines

And the 'lines': 和“线”:

cd $APP && pwd

If I bash test.sh , it prints out 'cd $APP && pwd'. 如果我bash test.sh ,它将打印出“ cd $ APP && pwd”。

But when I type APP=/apps echo "cd $APP && pwd" in the terminal, it prints out 'cd /apps && pwd'. 但是,当我在终端中键入APP=/apps echo "cd $APP && pwd"时,它会打印出'cd / apps && pwd'。

Is it possible using echo to extract variables which are reading from a regular file? 是否可以使用echo提取从常规文件读取的变量?

Depending on the contents of the file, you may want to use eval: 根据文件的内容,您可能需要使用eval:

#!/bin/bash
APP=/apps
while read line; do
    eval "echo \"$line\""  # WARNING: dangerous
done < ./lines

However, eval is extremely dangerous. 但是,评估非常危险。 Although the quoting here will work for simple cases, it is quite easy to execute arbitrary commands by manipulating the input. 尽管这里的引用适用于简单情况,但是通过操纵输入执行任意命令是很容易的。

您应该使用eval评估从文件读取的字符串行

如果知道要替换的变量,只需替换它们即可。

sed 's%\$APP\>%/apps%g' ./lines

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM