我编写了 shell 脚本中的函数来从文件读取变量设置或将变量设置写入文件。我想知道是否有更干净的方法来做到这一点。我特别不喜欢删除现有的写入匹配项,然后在文件末尾重写。有一个更好的方法吗?谢谢。
fnReadTestSetting()
{
#$1 is the variable to be read from the testsettings.ini file
grep $1 $MAIN_FOLDER/testsettings.ini >$MAIN_FOLDER/temp.ini
if [ $? -eq 0 ]; then
sed -i "s|$1=||" $MAIN_FOLDER/temp.ini
TEST_VALUE=`cat $MAIN_FOLDER/temp.ini`
export $1=$TEST_VALUE
fi
rm $MAIN_FOLDER/temp.ini
return
}
fnWriteTestSetting()
{
#$1 is the variable and value to be written to the testsettings.ini file in the format VARIABLE_NAME=VALUE
if [ ! -e $MAIN_FOLDER/testsettings.ini ]; then
touch $MAIN_FOLDER/testsettings.ini
fi
SETTING_NAME=`echo $1 | awk -F = '{print $1}'`
grep $SETTING_NAME $MAIN_FOLDER/testsettings.ini &>/dev/null
if [ $? -eq 0 ]; then
sed -i "/^$SETTING_NAME/d" $MAIN_FOLDER/testsettings.ini
echo "$1" >> $MAIN_FOLDER/testsettings.ini
else
echo "$1" >> $MAIN_FOLDER/testsettings.ini
fi
return
}
最佳答案
我做了一些改进:
您可以使用单个 sed 来读取设置。这可以节省对 tmp 文件的写入。不确定您为什么要尝试导出 1 美元。
fnReadTestSetting()
{
#$1 is the variable to be read from the testsettings.ini file
sed -n "s/^$1=\(.*$\)/\1/p" $MAIN_FOLDER/testsettings.ini
}
对于写入,如果文件不存在,则无需触摸该文件,因为无论如何都会创建它。您不需要 awk 来查找设置名称。您还可以将 grep 作为 if 语句中的条件,而不是显式检查其退出代码。使用单个 sed 进行替换(而不是删除和回显)。
fnWriteTestSetting()
{
#$1 is the variable and value to be written to the testsettings.ini file in the format VARIABLE_NAME=VALUE
SETTING_NAME=${1%%=*}
if grep -sq "^${SETTING_NAME}=" $MAIN_FOLDER/testsettings.ini
then
sed -i "s/^${SETTING_NAME}=.*$/$1/" $MAIN_FOLDER/testsettings.ini
else
echo "$1" >> $MAIN_FOLDER/testsettings.ini
fi
return
}
更新:
%%=*
删除 =
之后的所有内容。有关 %%
运算符的更多信息,请查看 string manipulation guide :
${string%%substring}
Deletes longest match of $substring from back of $string.
关于bash - 如何改进读取变量值并将其写入文件的逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5038852/