【问题标题】:Referencing bash variable name from separate file [duplicate]从单独的文件中引用 bash 变量名 [重复]
【发布时间】:2018-03-29 00:31:13
【问题描述】:

假设有两个文件:file1file2file1 是一个简短的 Bash 脚本,它引用 file2 以获取文本字符串。文本字符串包含一个变量名 ($VAR1),但变量本身在 file1 中分配了一个值。

$ cat file1
#!/bin/bash
VAR1="World"
CMDS=$(cat file2)
echo "$CMDS"

$ cat file2
Hello $VAR1 !

上述设置下,file1执行过程中变量名无法正确识别。

$ bash file1 
Hello $VAR1 !

file1的执行过程中,我需要做什么才能正确识别变量名?

【问题讨论】:

  • 你为什么要这样做?
  • @123 显然,他想使用bash作为模板系统。
  • @chepner 处理模板的方式非常奇怪。

标签: bash shell variables


【解决方案1】:

由于你不执行file2,只是cat它的内容,file2中的变量只作为一个占位符。您可以将输出从 cat 传输到 sed,如下所示:

CMDS=$(cat file2|sed -e "s/\$VAR1/$VAR1/")

【讨论】:

猜你喜欢
  • 2018-05-23
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-09
  • 2021-07-30
  • 1970-01-01
  • 2011-05-25
相关资源
最近更新 更多