【发布时间】:2016-07-01 15:35:46
【问题描述】:
因此,我阅读了将 .conf 文件用于 bash 脚本的最简单方法是使用 source 加载此类文件。现在,如果我想编辑这个文件怎么办?
我发现的一些代码做得很好:
function set_config(){
sed -i "s/^\($1\s*=\s*\).*\$/\1$2/" $conf_file
}
但是,如果变量还没有定义,它就不会定义它,也不会检查参数是否传递良好、不安全、不处理默认值等......
是否已经存在可靠的工具/代码来编辑包含 key="value" 对的 .conf 文件?例如,我希望能够做这样的事情:
$conf_file="my_script.conf"
conf_load $conf_file #should create the file if it doesn't exist !
read=$(conf_get_value "data" "default_value") #should read the value with key "data", defaulting to "default_value"
if [[ $? = 0 ]] #we should be able to know if the read was successful
then
echo "Successfully read value for field \"data\" : $read"
else
echo "Default value for field \"data\" : $read"
fi
conf_set "something_new" "a great value!" #should add the key "something_new" as it doesn't exist
conf_set "data" "new_value" #should edit the value with key "data"
if [[ $? = 0 ]]
then
echo "Edit successful !"
else #something went wrong :-/
echo "Edit failed !"
fi
在运行此代码之前,conf 文件将包含
data="some_value"
然后是
data="new_value"
something_new="a great value!"
并且代码应该输出
Successfully read value for field "data" : some_value
Edit successful !
我正在使用 bash 版本 4.3.30 。
感谢您的帮助。
【问题讨论】:
-
你能给我们举一些数据前后的例子吗?
-
@Mr.Llama 编辑问题以使其更清晰
标签: bash security config configuration-files