bash bash脚本将文件变量读入局部变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12273948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:12:04  来源:igfitidea点击:

bash script read file variables into local variables

bashvariablesfile-io

提问by thegreat078

I have a config file with the following content:

我有一个包含以下内容的配置文件:

msgs.config:

msgs.config:

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

I am writing a bash script that reads the msgs.config file variables and stores them into local variables. I will use these throughout the script. Due to permission I do not want to use the .method (source).

我正在编写一个 bash 脚本,它读取 msgs.config 文件变量并将它们存储到局部变量中。我将在整个脚本中使用这些。由于许可,我不想使用该.方法(来源)。

tmsg
t1msg
t2msg
pmsg

Any help would be greatly appreciated.

任何帮助将不胜感激。

回答by Jonathan Leffler

You can use:

您可以使用:

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

Alternatively, you can use an associative array:

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

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

Now you can refer to ${keys[tmsg]}etc to access the variables. Or, if the list of variables is fixed, you can map the values to variables:

现在您可以参考${keys[tmsg]}etc 来访问变量。或者,如果变量列表是固定的,您可以将值映射到变量:

tmsg="${keys[tmsg]}"

回答by AnBisw

Read the file and store the values-

读取文件并存储值-

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

Access the array variables as ${key[0]},${key[1]},.... and ${val[0]},${val[1]}...

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

回答by chepner

In case you change your mind about source:

如果您改变主意source

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

This does not work if any of your values have double quotes.

如果您的任何值有双引号,这将不起作用。