如何在bash中读取包含空格和需要转义的其他字符的环境变量?
我有一个文件server.env
PUBLIC_KEY=ssh-rsa whatever+whatever+8whatever/whatever+p+whatever user@alans-MacBook-Pro.local我试图将这个文件作为环境变量读入bash脚本:
export $(cat server.env | xargs)我收到了一个错误:
-bash: export: `user@alans-MacBook-Pro.local': not a valid identifier好的,尝试引用server.env中的值:
PUBLIC_KEY='ssh-rsa whatever+whatever+8whatever/whatever+p+whatever user@alans-MacBook-Pro.local'双引号:
PUBLIC_KEY="ssh-rsa whatever+whatever+8whatever/whatever+p+whatever user@alans-MacBook-Pro.local"我在这里错过了什么?
发布于 2021-01-24 06:45:07
Bash提供了带有子字符串删除的参数扩展,这将允许您将从NAME=value文件中读取的server.env对分离出来,然后对NAME=value对进行export。
只需要一个简单的read循环:
#!/bin/bash
while read -r line; do ## read each line of server.env
val="${line#*=}" ## trim to 1st =, save in val
export ${line%=$val}="$val" ## remove =$val leaving name, export val with name
done < server.env
printf "%s\n" "$PUBLIC_KEY" ## confirm示例使用/输出
$ bash test.sh
ssh-rsa whatever+whatever+8whatever/whatever+p+whatever user@alans-MacBook-Pro.local其中基本参数展开是:
${var#pattern} Strip shortest match of pattern from front of $var
${var##pattern} Strip longest match of pattern from front of $var
${var%pattern} Strip shortest match of pattern from back of $var
${var%%pattern} Strip longest match of pattern from back of $var(注意: pattern可以包含普通的shell球体,如'*'和'?')
实际上,有许多有用的参数扩展可以用于字符串操作。只需在man bash标题下检查"Parameter Expansion"。
发布于 2021-01-24 04:17:00
部分应答(不export,因此变量在以后的bash运行中不可用,仅在当前会话中):
source server.env发布于 2021-01-24 04:17:08
这里的问题是,字段分裂仍然发生在空格上。
你应该这么做:
export "$(cat server.env)"(即加双引号)。
对于多个变量,在行上循环如下:
while read -r line
do
export "$line"
done < server.env如果这是在一个名为export.sh的脚本中,那么您还需要对当前进程中要设置的变量进行source:
source export.shhttps://stackoverflow.com/questions/65867051
复制相似问题