从另一个文件导入变量

sin*_*rba 2 bash shell-script

我有一个脚本文件:

#!/usr/bin/env bash

. /home/$USER/git_projects/cfhookbash/config.txt

deploy_challenge() {
}
Run Code Online (Sandbox Code Playgroud)

在 config.txt 中有 www.example.com_token="asdfasdf"

www.example.com_token在我的示例中,我需要打印(或重用) 的值asdfasdf

我得到 /home/sineverba/git_projects/cfhookbash/config.txt: line 1: www.k2p.it_token=asdfasdf: command not found

Sté*_*las 6

在 中bash,变量名只能由单字节字母数字字符或下划线组成(第一个字符不能是数字)。

因此,www.example.com_token不是一个有效的变量名, www.example.com_token="asdfasdf"不被识别为赋值,而是一个简单的命令。

在 ksh93(shellbash试图模拟)中,www.example.com_token="asdfasdf"只有将www变量定义为复合变量时才有效:

$ compound www
$ www.example.com_token="asdfasdf"
$ typeset -p www
typeset -C www=(example=(com_token=asdfasdf))
$ printf '%s\n' "${www.example.com_token}"
asdfasdf
Run Code Online (Sandbox Code Playgroud)

在 中bash,您可能会使用关联数组变量(由 复制的 ksh93 功能之一bash):

typeset -A token
token[www.example.com]=asdfasdf
printf '%s\n' "${token[www.example.com]}"
Run Code Online (Sandbox Code Playgroud)

(该语法也应该适用于ksh93zsh)。

如果您无法修改它 config.txt以使其与您的 shell 语法兼容,您可以在评估之前对其进行动态编辑。喜欢(带有ksh93,bashzsh):

typeset -A token
. <(sed 's/^\([^=]*\)_token=/token[\1]=/' < config.txt)
Run Code Online (Sandbox Code Playgroud)

转换x.y_token=token[x.y]=或:

. <(sed -e :1 -e 's/^\([^=]*\)\.\(.*=\)/\1_\2/; t1' < config.txt)
Run Code Online (Sandbox Code Playgroud)

要更换每一个.的左侧=_

但请注意,其中任何一个都可以在不希望出现的地方进行替换,例如:

foo.bar_token="multi
line .x. _token assignment (=)"
Run Code Online (Sandbox Code Playgroud)

或者,如果文件不只包含作业。

现在,如果这config.txt实际上不包含正确的 shell 语法,您需要注意其他语法问题,例如包含的行foo="price: $12"foo="x `y' z"那些$,`是 shell 语法中的特殊运算符。