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

发布于 2024-10-17 15:54:24 字数 259 浏览 4 评论 0原文

我有一个文件,就像

name1=value1
name2=value2

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

$name1=value1
$name2=value2

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

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

I have a file like

name1=value1
name2=value2

I need to read this file using shell script and set variables

$name1=value1
$name2=value2

Please provide a script that can do this.

I tried the first answer below, i.e. sourcing the properties file but I'm getting a problem if the value contains spaces. It gets interpreted as a new command after the space. How can I get it to work in the presence of spaces?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

长发绾君心 2024-10-24 15:54:24

如果输入文件中的所有行都是这种格式,那么只需获取它就会设置变量:

source nameOfFileWithKeyValuePairs

. nameOfFileWithKeyValuePairs

If all lines in the input file are of this format, then simply sourcing it will set the variables:

source nameOfFileWithKeyValuePairs

or

. nameOfFileWithKeyValuePairs
纸短情长 2024-10-24 15:54:24

使用:

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

Use:

while read -r line; do declare  "$line"; done <file
独留℉清风醉 2024-10-24 15:54:24

使用 .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"
}

Sourcing the file using . or source has the problem that you can also put commands in there that are executed. If the input is not absolutely trusted, that's a problem (hello rm -rf /).

You can use read to read key value pairs like this if there's only a limited known amount of keys:

read_properties()
{
  file="$1"
  while IFS="=" read -r key value; do
    case "$key" in
      "name1") name1="$value" ;;
      "name2") name2="$value" ;;
    esac
  done < "$file"
}
混浊又暗下来 2024-10-24 15:54:24

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

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

if your file location is /location/to/file and the key is mykey:

grep mykey $"/location/to/file" | awk -F= '{print $2}'
眼中杀气 2024-10-24 15:54:24

@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`"

我尝试做最好逃跑,但我不确定这是否足够)

Improved version of @robinst

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

Changes:

  • Dynamic key mapping instead of static
  • Supports (skips) comment lines

A nice one is also the solution of @kurumi, but it isn't supported in busybox

And here a completely different variant:

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

(i tried to do best with escaping, but I'm not sure if that's enough)

貪欢 2024-10-24 15:54:24

假设您的文件名是 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"

suppose the name of your file is 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"
听你说爱我 2024-10-24 15:54:24
    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"
    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"
独自←快乐 2024-10-24 15:54:24

使用 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]...)"

Use shdotenv

dotenv support for shell and POSIX-compliant .env syntax specification
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

Load the .env file into your shell script.

eval "$(shdotenv [OPTION]...)"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文