简体   繁体   中英

Bash: echo extract variables

Suppose there's a script called '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'.

But when I type APP=/apps echo "cd $APP && pwd" in the terminal, it prints out 'cd /apps && pwd'.

Is it possible using echo to extract variables which are reading from a regular file?

Depending on the contents of the file, you may want to use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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