所以我读了bash
脚本使用.conf文件的最简单方法,就是使用source
来加载这样的文件。现在,如果我想编辑这个文件呢?如何轻松编辑.conf文件?
一些代码,我发现做了很好的工作:
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。 感谢您的帮助。
你能给我们一些例子之前和之后的数据? –
@Llama先生编辑这个问题,使其更清晰 – Magix