我有一个像
name1=value1
name2=value2
我需要使用 shell 脚本读取这个文件并设置变量
$name1=value1
$name2=value2
请提供可以执行此操作的脚本。
我尝试了下面的第一个答案,即获取属性文件,但如果值包含空格,我会遇到问题。它被解释为空格后的新命令。我怎样才能让它在有空间的情况下工作?
我有一个像
name1=value1
name2=value2
我需要使用 shell 脚本读取这个文件并设置变量
$name1=value1
$name2=value2
请提供可以执行此操作的脚本。
我尝试了下面的第一个答案,即获取属性文件,但如果值包含空格,我会遇到问题。它被解释为空格后的新命令。我怎样才能让它在有空间的情况下工作?
如果输入文件中的所有行都是这种格式,那么只需对其进行采购就会设置变量:
source nameOfFileWithKeyValuePairs
或者
. nameOfFileWithKeyValuePairs
采用:
while read -r line; do declare "$line"; done <file
使用.
或获取文件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"
}
如果您的文件位置是/location/to/file
并且密钥是mykey
:
grep mykey $"/location/to/file" | awk -F= '{print $2}'
假设你的文件名是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"
@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`"
(我试图在逃避方面做得最好,但我不确定这是否足够)
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]...)"
sed 's/^/\$/' yourfilename