#!/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"
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
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"
8条答案
按热度按时间d6kp6zgx1#
如果输入文件中的所有行都是这种格式,那么简单地提取它将设置变量:
字符串
或者是
型
q3aa05252#
用途:
字符串
x759pob23#
使用
.
或source
获取文件的问题是,您也可以将执行的命令放在那里。如果输入不是绝对可信的,那就有问题了(hellorm -rf /
)。如果已知的键数量有限,可以使用
read
来读取键值对:字符串
yizd12fk4#
如果你的文件位置是
/location/to/file
,键是mykey
:字符串
iyfamqjs5#
@robinst的改进版本
字符串
变更:
@kurumi的解决方案也不错,但busybox不支持
这里有一个完全不同的变体:
型
(我已经尽力了,但我不确定这是否足够)
mwg9r5ms6#
假设文件名为
some.properties
字符串
zynd9foi7#
使用shdotenv
dotenv支持shell和符合POSIX的.env语法规范https://github.com/ko1nksm/shdotenv
字符串
将.env文件加载到shell脚本中。
型
gkl3eglg8#
字符串