bash - 如何改进读取变量值并将其写入文件的逻辑?

标签 bash file shell variables

我编写了 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/

相关文章:

c - 相当于 shell bash 中的 "(cond)? val_true : val_false"

perl - 如何将 Bash Shell 命令的输出逐行传输到 Perl 以进行正则表达式处理?

mysql - 请解释一下这个 Shell 管道魔法 (... | tee >(tail -c1 >$PULSE) | bzip2 | ...) 是如何工作的?

c - fscanf 不从文件读取

bash - `test -n $a` 和 `test -n "$a"` 之间的区别

shell - 在 shell 的同一行中设置和使用 docker alpine 中的环境变量

linux - rm : cannot remove: Permission denied

linux - 检查 Linux text/fb 控制台当前是否按住 shift 键

java - 在写入文件时从文件中读取数据

c - 即使在程序中提供了正确的路径后,我也无法在 Visual C++ 中打开该文件