需要bash shell脚本从文件中阅读名称/值对

isr3a4wc  于 2023-08-07  发布在  Shell
关注(0)|答案(8)|浏览(110)

我有一个文件

name1=value1
name2=value2

字符串
我需要读取这个文件使用shell脚本和设置变量

$name1=value1
$name2=value2


请提供一个脚本,可以做到这一点。
我尝试了下面的第一个答案,即。源属性文件,但我得到了一个问题,如果值包含空格。它被解释为空格后的新命令。我怎样才能让它在有空间的情况下工作呢?

d6kp6zgx

d6kp6zgx1#

如果输入文件中的所有行都是这种格式,那么简单地提取它将设置变量:

source nameOfFileWithKeyValuePairs

字符串
或者是

. nameOfFileWithKeyValuePairs

q3aa0525

q3aa05252#

用途:

while read -r line; do declare  "$line"; done <file

字符串

x759pob2

x759pob23#

使用.source获取文件的问题是,您也可以将执行的命令放在那里。如果输入不是绝对可信的,那就有问题了(hello rm -rf /)。
如果已知的键数量有限,可以使用read来读取键值对:

read_properties()
{
  file="$1"
  while IFS="=" read -r key value; do
    case "$key" in
      "name1") name1="$value" ;;
      "name2") name2="$value" ;;
    esac
  done < "$file"
}

字符串

yizd12fk

yizd12fk4#

如果你的文件位置是/location/to/file,键是mykey

grep mykey $"/location/to/file" | awk -F= '{print $2}'

字符串

iyfamqjs

iyfamqjs5#

@robinst的改进版本

read_properties()
{
  file="$1"
  while IFS="=" read -r key value; do
    case "$key" in
      '#'*) ;;
      *)
        eval "$key=\"$value\""
    esac
  done < "$file"
}

字符串
变更:

  • 动态键Map代替静态键Map
  • 支持(跳过)注解行

@kurumi的解决方案也不错,但busybox不支持
这里有一个完全不同的变体:

eval "`sed -r -e "s/'/'\\"'\\"'/g" -e "s/^(.+)=(.+)\$/\1='\2'/" $filename`"


(我已经尽力了,但我不确定这是否足够)

mwg9r5ms

mwg9r5ms6#

假设文件名为some.properties

#!/bin/sh
# Sample shell script to read and act on properties

# source the properties:
. some.properties

# Then reference then:
echo "name1 is $name1 and name2 is $name2"

字符串

zynd9foi

zynd9foi7#

使用shdotenv

dotenv支持shell和符合POSIX的.env语法规范https://github.com/ko1nksm/shdotenv

Usage: shdotenv [OPTION]... [--] [COMMAND [ARG]...]

  -d, --dialect DIALECT  Specify the .env dialect [default: posix]
                           (posix, ruby, node, python, php, go, rust, docker)
  -s, --shell SHELL      Output in the specified shell format [default: posix]
                           (posix, fish)
  -e, --env ENV_PATH     Location of the .env file [default: .env]
                           Multiple -e options are allowed
  -o, --overload         Overload predefined environment variables
  -n, --noexport         Do not export keys without export prefix
  -g, --grep PATTERN     Output only those that match the regexp pattern
  -k, --keyonly          Output only variable names
  -q, --quiet            Suppress all output
  -v, --version          Show the version and exit
  -h, --help             Show this message and exit

字符串
将.env文件加载到shell脚本中。

eval "$(shdotenv [OPTION]...)"

gkl3eglg

gkl3eglg8#

filename="config.properties"

# Read the file and extract key-value pairs
while IFS='=' read -r key value; do
    # Skip empty lines or lines starting with #
    if [[ -z $key || $key == \#* ]]; then
        continue
    fi

    # Trim leading/trailing whitespace from key
    key=$(echo "$key" | awk '{gsub(/^ +| +$/,"")} {print $0}')

    # Extract the value after the first equals sign
    value="${line#*=}"
    
    # Assign value to the variable dynamically
    declare "$key"="$value"
done < "$filename"

# Print the variables
echo "key1: $key1"
echo "key2: $key2"
echo "key3: $key3"

字符串

相关问题