在bash中即时分配变量值 [英] Assigning variable values on the fly in bash

查看:75
本文介绍了在bash中即时分配变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下配置文件:OO_CONF.conf,其中包含以下内容:

I have the below config file : OO_CONF.conf with the below contents:

appPackage_name = sqlncli
appPackage_version = 11.3.6538.0

现在,我想在我的shell脚本中读取这些变量.所以我想要一个变量$ appPackage_name,它应该包含值:sqlncli

Now i want to read these variables inside my shell script. So i want a variable $appPackage_name and it should contain the value: sqlncli

我试图做到的方式是:

while read line; do
  newline=`echo $line | sed -e 's/ //g'`
  expr "$newline"
done < ./OO_CONF.conf

echo "$appPackage_name"

但这似乎不起作用.

请对此寻求帮助.

推荐答案

使用 <内置在 bash 中并带有 -g 标志的code> declare 使其在全球范围内可用,

Use the declare built-in in bash with -g flag to make it globally available,

#!/bin/bash

while IFS=' = ' read -r  key value; do
    declare -g $key="$value"
done <OO_CONF.conf

printf "%s %s\n" "${appPackage_name}" "${appPackage_version}"

想法是将 IFS 设置为 = ,以便拆分文件中的行以读取键和值对,然后使用 declare 我们可以使用以下语法即时创建变量

The idea is to set the IFS to = so to split the lines in the file to read the key and value pairs and then with declare we can create variables on the fly with the below syntax

declare -g <var-name>=<variable-value>

这篇关于在bash中即时分配变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆