Bash脚本读取文件变量到本地变量

7
我有一个配置文件,内容如下:

msgs.config:

tmsg:This is Title Message!
t1msg:This is T1Message.    
t2msg:This is T2Message.    
pmsg:This is personal Message!

我正在编写一个bash脚本,它会读取msgs.config文件中的变量并将它们存储到本地变量中。我将在整个脚本中使用这些变量。由于权限问题,我不想使用.方法(source)。
tmsg
t1msg
t2msg
pmsg

任何帮助都将不胜感激。

1
由于权限问题,我不想使用“.”方法(源代码)。不确定它如何帮助,但您只需要读取权限即可使用“source”,如果您无法阅读它... - cdarke
3个回答

8

您可以使用:

oldIFS="$IFS"
IFS=":"
while read name value
do
    # Check value for sanity?  Name too?
    eval $name="$value"
done < $config_file
IFS="$oldIFS"

或者,您可以使用关联数组:

declare -A keys
oldIFS="$IFS"
IFS=":"
while read name value
do
    keys[$name]="$value"
done < $config_file
IFS="$oldIFS"

现在您可以通过 ${keys[tmsg]} 等方式来访问变量。或者,如果变量列表是固定的,您可以将值映射到变量:
tmsg="${keys[tmsg]}"

1
不需要保存 oldIFS,你可以在 while IFS=: read name value 命令中限制对 IFS 的更改。此外,使用 declare "$name=$value" 而不是 eval - chepner
感谢你的所有帮助。你建议:oldIFS="$IFS" IFS=":" while IFS=: read name value do declare "$name=$value" done < $config_file - thegreat078
@thegreat078:建议完全避免使用oldIFS,而是在循环中使用while IFS=':' read name value(这样您就不需要在循环后重置IFS)。假设它可行,那么这是合理的。如果declare $name="$value"符号工作正常(我没有理由认为它不工作,但被卡在一个没有关联数组的Bash 3.2机器上),那么这绝对比eval容易出错得多(几乎总是玩火,但有时是必要的;另一方面,Bash已经做了很多使其不再像以前那样必要的事情,这是一件好事™!) - Jonathan Leffler
Jonathan Leffler:好的,我刚试了一下。在我的bash中,declare $name="$value"没有起作用。我使用了eval,它可以正常工作。我猜这可能因机器而异。感谢所有的帮助。在我获得15个声望之前,我无法投票。 - thegreat078

1

如果你改变了对于源代码的想法:

source <( sed 's/:\(.*\)/="\1"/' msgs.config )

如果您的任何值都有双引号,这将无法正常工作。


1

读取文件并存储数值-

i=0
config_file="/path/to/msgs.config"

while read line
do
  if [ ! -z "$line" ]  #check if the line is not blank
  then
   key[i]=`echo $line|cut -d':' -f1`  #will extract tmsg from 1st line and so on
   val[i]=`echo $line|cut -d':' -f2`  #will extract "This is Title Message!" from line 1 and so on
   ((i++))
  fi
done < $config_file

访问数组变量的方式为 ${key[0]}${key[1]},... 和 ${val[0]}${val[1]},...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接