28

我有一个像

name1=value1
name2=value2

我需要使用 shell 脚本读取这个文件并设置变量

$name1=value1
$name2=value2

请提供可以执行此操作的脚本。

我尝试了下面的第一个答案,即获取属性文件,但如果值包含空格,我会遇到问题。它被解释为空格后的新命令。我怎样才能让它在有空间的情况下工作?

4

8 回答 8

28

如果输入文件中的所有行都是这种格式,那么只需对其进行采购就会设置变量:

source nameOfFileWithKeyValuePairs

或者

. nameOfFileWithKeyValuePairs
于 2011-02-14T09:41:43.597 回答
16

采用:

while read -r line; do declare  "$line"; done <file
于 2011-02-14T09:49:21.450 回答
16

使用.或获取文件source的问题是,您还可以将执行的命令放入其中。如果输入不是绝对可信的,那就是一个问题(你好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"
}
于 2014-09-05T05:09:02.853 回答
10

如果您的文件位置是/location/to/file并且密钥是mykey

grep mykey $"/location/to/file" | awk -F= '{print $2}'
于 2018-09-05T11:14:34.997 回答
6

假设你的文件名是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"
于 2011-02-14T09:45:15.693 回答
6

@robinst 的改进版本

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

变化:

  • 动态键映射而不是静态
  • 支持(跳过)注释行

一个不错的也是@kurumi的解决方案,但busybox不支持

这里有一个完全不同的变体:

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

(我试图在逃避方面做得最好,但我不确定这是否足够)

于 2015-01-13T09:26:18.820 回答
0

使用 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]...)"
于 2021-08-25T23:53:08.643 回答
-6

sed 's/^/\$/' yourfilename

于 2011-02-14T11:12:30.660 回答